Home »
Java »
Java Programs
Java program to create a TreeSet collection using List collection
Given a List collection, we have to create a TreeSet collection using it.
Submitted by Nidhi, on June 04, 2022
Problem statement
In this program, we will create a TreeSet collection with integer elements using the List collection. Here, we will pass the List collection into the constructor of the TreeSet collection.
Java program to create a TreeSet collection using List collection
The source code to create a TreeSet collection using the List collection is given below. The given program is compiled and executed successfully.
// Java program to create a TreeSet collection
// using the List collection
import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[]) {
List list = new ArrayList();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
list.add(60);
TreeSet < Integer > tree = new TreeSet < Integer > (list);
System.out.println("TreeSet elements: " + tree);
}
}
Output
TreeSet: [10, 20, 30, 40, 50, 60]
Explanation
In the above program, we imported the "java.util.*", "java.io.*" packages to use the TreeSet class. Here, we created a public class Main.
The Main class contains a main() method. The main() method is the entry point for the program. And, created a List collection list and added integer elements using add() method. Then, we created a Tree collection tree using the constructor by passing the list as an argument. After that, we printed the result.
Java TreeSet Programs »