Write a Java program to create a TreeSet collection


The code demonstrates how to create and use a TreeSet in Java. In the Create_TreeSet class, a TreeSet object called col is created to store strings. Strings such as "Blue", "Red", "Green", "White", "Orange", "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.

Note: TreeSet is a collection class in Java that implements the Set interface and stores unique elements in sorted order. It does not allow duplicate elements, and provides efficient operations for adding, removing, and retrieving elements in sorted order.

Source Code

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

Output

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