TreeSet remove() method in java

Let’s learn TreeSet remove() method in java.

TreeSet remove() method in java

remove() method of TreeSet class removes the specified element from this set if it is present. More formally, removes an element e such that Objects.equals(o, e), if this set contains such an element.

Syntax:

public boolean remove(Object o)

Parameters:

o object to be removed from this set, if present.

Throws:

ClassCastException – if the specified object cannot be compared with the elements currently in this set.

NullPointerException – if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements.

Now let’s see example on TreeSet remove(Object o) method.

import java.util.TreeSet;
public class TreeSetRemoveMethodExample
{
   public static void main(String[] args)
   {
      TreeSet<String> ts = new TreeSet<String>();
      ts.add("orange");
      ts.add("green");
      ts.add("blue");
      ts.add("red");
      ts.add("violet");
      ts.add("yellow");
      System.out.println("Given TreeSet: " + ts);
      // remove elements using remove() method
      ts.remove("blue");
      ts.remove("violet");
      ts.remove("red");
      // print TreeSet after removal
      System.out.println("New TreeSet: " + ts);
   }
}

Output:

Given TreeSet: [blue, green, orange, red, violet, yellow]
New TreeSet: [green, orange, yellow]


Also read – foreach loop in java