Write a Java program to Remove a specified item from the TreeSet collection


The code demonstrates how to remove specified elements from a TreeSet in Java. In the Remove_Specified class, a TreeSet object called col is created to store strings. Strings such as "Blue", "Red", "White", "Orange", "Green", "Yellow", and "Pink" are added to the col set using the add method.

The System.out.println statement is used to print the elements in the col set, which will be displayed in a sorted order as TreeSet automatically sorts its elements based on their natural order or using a custom comparator if provided.

The col.remove() method is used to remove elements from the col set. In this example, "Red" and "Green" are removed from the set using the remove method. After the removal, the System.out.println statement is used again to print the updated elements in the col set, which will be displayed in a sorted order.

Note that the remove method in Java removes the first occurrence of the specified element from the set. If the specified element is not found in the set, the set remains unchanged. To remove all occurrences of a specified element, you can use a loop or other techniques to iterate through the set and remove all occurrences manually.

Source Code

import java.io.*;
import java.util.*;
public class Remove_Specified
{
	public static void main(String args[])
	{
		TreeSet <String> col = new TreeSet <String>();
		col.add("Blue");
		col.add("Red");
		col.add("White");
		col.add("Orange");
		col.add("Green");
		col.add("Yellow");
		col.add("Pink");
		System.out.println("TreeSet Element : " + col);
 
		col.remove("Red");
		col.remove("Green");
		System.out.println("Updated TreeSet : " + col);
	}
}

Output

TreeSet Element : [Blue, Green, Orange, Pink, Red, White, Yellow]
Updated TreeSet : [Blue, Orange, Pink, White, Yellow]