How to Remove Specified Element from TreeSet in Java


In this example we will show how to remove a specified object or element contained in Java TreeSet object using remove method.

Source Code

package com.beginner.examples;

import java.util.TreeSet;

public class RemoveSpecifiedElementFromTreeSet {

	public static void main(String[] args) {
		
	    //create TreeSet.
	    TreeSet treeSet = new TreeSet();
	   
	    treeSet.add("A");
	    treeSet.add("B");
	    treeSet.add("C");
	    treeSet.add("D");
	    
	    System.out.println("Before removal , treeSet contains : " + treeSet);
	    
	    /*
	     *  To remove an element from Java TreeSet object use remove() method.
	     */
	    treeSet.remove("C");
	    System.out.println("After removal , treeSet contains : " + treeSet);
	    

	}

}

Output:

Before removal , treeSet contains : [A, B, C, D]
After removal , treeSet contains : [A, B, D]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments