Skip to content

How to Remove Elements from Java TreeSet Example

This example shows how to remove elements from the TreeSet in Java. This example also shows how to remove the specified element, first element, last element or all elements from the TreeSet object.

How to remove elements from TreeSet in Java?

There are several methods using which we can remove elements from the TreeSet in Java.

1. Removing the specified element

The remove method removes the specified element from the TreeSet object.

The remove method removes the given element from the TreeSet and returns true if found. If the specified element is not found, the set remains unchanged and it returns false.

Output

If the TreeSet contains the custom class object elements, we can remove the elements in the same way.

Output

The TreeSet elements must implement the Comparable interface or a custom comparator must be provided when the TreeSet object is created.

2. Removing the first or last element

The pollFirst and pollLast methods remove the first and last elements of the TreeSet respectively.

Output

Please visit how to get first and last elements from the TreeSet example to know more.

3. Removing all elements

The clear method of the TreeSet class removes all elements of the TreeSet object.

Output

Please visit how to clear or remove all elements from the Treeset example and how to check if the TreeSet is empty example to know more.

This example is a part of the Java TreeSet Tutorial with Examples.

Please let me know your views in the comments section below.

References:
Java 8 TreeSet

About the author

Leave a Reply

Your email address will not be published.