How to Create a TreeSet with a List in Java?
TreeSet is an implementation of the SortedSet interface in Java that uses a Tree for storage. TreeSet can be created from List by passing the List to the TreeSet constructor in Java or we can traverse complete List and adding each element of the List to the TreeSet.
Example:
Input : List = [a, b, c] Output: TreeSet = [a, b, c] Input : List = [1, 2, 3] Output: TreeSet = [1, 2, 3]
Approach 1:
- Create a List object.
- Enter multiple inputs in the List.
- Create a TreeSet Object.
- Initialize object with a constructor and pass List object in it.
- Print the Treeset.
Below is the implementation of the above approach:
Java
// Java Program to Create a TreeSet with a Listimport java.util.ArrayList;import java.util.List;import java.util.TreeSet;public class ExampleTreeSet { public static void main(String a[]) { // Create new List List<String> fruitlist = new ArrayList<String>(); fruitlist.add("Mango"); fruitlist.add("Apple"); fruitlist.add("Grape"); fruitlist.add("Papaya"); // Printing ArrayList System.out.println("Fruit List : " + fruitlist); // Create a TreeSet with the list TreeSet<String> tree_set = new TreeSet<String>(fruitlist); // Print TreeSet System.out.println("TreeSet from List : " + tree_set); }} |
Fruit List : [Mango, Apple, Grape, Papaya] TreeSet from List : [Apple, Grape, Mango, Papaya]
Time Complexity: O(N)
Approach 2:
- Create a List object.
- Enter multiple inputs in the List.
- Create a TreeSet Object.
- Start List traversal and add that element in the TreeSet.
- After complete traversal, Print the Treeset.
Below is the implementation of the above approach:
Java
// Java Program to Create a TreeSet with a Listimport java.util.ArrayList;import java.util.List;import java.util.TreeSet;public class ExampleTreeSet { public static void main(String a[]) { // Create new List List<String> fruitlist = new ArrayList<String>(); fruitlist.add("Mango"); fruitlist.add("Apple"); fruitlist.add("Grape"); fruitlist.add("Papaya"); // Printing ArrayList System.out.println("Fruit List : " + fruitlist); // Create a TreeSet TreeSet<String> tree_set = new TreeSet<String>(); // Add each element in the TreeSet for (String i : fruitlist) tree_set.add(i); // Print TreeSet System.out.println("TreeSet from List : " + tree_set); }} |
Fruit List : [Mango, Apple, Grape, Papaya] TreeSet from List : [Apple, Grape, Mango, Papaya]
Time Complexity: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.


