Removing an Element from TreeSet in Java - remove(Object o)

In this example, we'll show you how to remove an element from TreeSet using the java.util.TreeSet.remove().

The remove(Object o) is used to remove a specific item from the TreeSet if it exists in the list. The remove() returns true if the element exists in the TreeSet, otherwise false.

To remove an element from the TreeSet and distinguish the difference before and after the deletion, follow these steps:
  • Create a TreeSet.
  • Populate this TreeSet with elements, using the add(Object o).
  • Browse and view items in TreeSet.
  • Delete an item by calling the remove(Object o).
  • Show the list a second time to see the difference.
The following code implements these five steps and prints the result:

import java.util.Iterator; 
import java.util.TreeSet;

public class main {
public static void main(String[] args) {
// creating a TreeSet
TreeSet treerem = new TreeSet();

// add values to TreeSet
treerem.add(2);
treerem.add(4);
treerem.add(6);
treerem.add(8);

// create an iterator to iterate through TreeSet
Iterator iterator = treerem.iterator();

// display all TreeSet elements
System.out.println("TreeSet elements");
while (iterator.hasNext()){
System.out.println(iterator.next());
}

//call to the remove()
boolean exists = treerem.remove(4);
System.out.println("4 exists? " +exists);

iterator = treerem.iterator();
// show all TreeSet elements after deletion
System.out.println("TreeSet elements");
while (iterator.hasNext()){
System.out.println(iterator.next());
}

}
}
Let's compile and execute this code, it will produce the following result:

TreeSet
2
4
6
8
4 exists? true
TreeSet elements
2
6
8
References:
java.util.TreeSet.remove() Method