Java TreeSet remove(Object o) Example

The remove(Object o) method will remove the first occurrence of the element from the treeset if it is present. If the element is not present then it leaves the treeset untouched

Signature

public boolean remove(Object o)

This method removes the first occurrence of the element of the treeset and returns true if the removal was successful.

Example

The following example shows the usage of java.util.TreeSet.remove(o) method.

import java.util.TreeSet;

public class RemoveMethodTreeSetExample 
{
    public static void main(String args[])
    {
        // create an empty TreeSet
        TreeSet<String> treeSet1 = new TreeSet<String>();
        
        // use add() method to add elements to the TreeSet
        treeSet1.add("Element1");
        treeSet1.add("Element2");
        treeSet1.add("Element3");
        
        //Printing the elements of the TreeSet
        System.out.println("**Elements of the TreeSet before remove**");
        for(String temp:treeSet1)
        {
            System.out.println(temp);
        }
        
        //Removing the "Element1" from the TreeSet
        boolean flag = treeSet1.remove("Element2");
        System.out.println("Is the removal successful ?? "+flag);
        
        //Printing the elements of the TreeSet
        System.out.println("**Elements of the TreeSet after remove**");
        for(String temp:treeSet1)
        {
            System.out.println(temp);
        }
    }
}

Output

**Elements of the TreeSet before remove**
Element1
Element2
Element3
Is the removal successful ?? true
**Elements of the TreeSet after remove**
Element1
Element3

Leave a Reply

Your email address will not be published. Required fields are marked *