Write a Java program to create a TreeSet collection using List collection


This is a Java program that demonstrates how to create a TreeSet object from an existing List using the TreeSet constructor that takes a Collection as an argument.

The program first creates an ArrayList called col and adds seven string elements to it using the add() method.

Then, the program creates a new TreeSet object called tree and passes the col list to its constructor. This creates a new TreeSet object containing the same elements as the col list, but sorted in their natural order.

Finally, the program prints the contents of the tree set to the console using the println() method.

Source Code

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

Output

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