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
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
public class ExampleTreeSet {
public static void main(String a[])
{
List<String> fruitlist = new ArrayList<String>();
fruitlist.add( "Mango" );
fruitlist.add( "Apple" );
fruitlist.add( "Grape" );
fruitlist.add( "Papaya" );
System.out.println( "Fruit List : " + fruitlist);
TreeSet<String> tree_set
= new TreeSet<String>(fruitlist);
System.out.println( "TreeSet from List : "
+ tree_set);
}
}
|
OutputFruit 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
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
public class ExampleTreeSet {
public static void main(String a[])
{
List<String> fruitlist = new ArrayList<String>();
fruitlist.add( "Mango" );
fruitlist.add( "Apple" );
fruitlist.add( "Grape" );
fruitlist.add( "Papaya" );
System.out.println( "Fruit List : " + fruitlist);
TreeSet<String> tree_set = new TreeSet<String>();
for (String i : fruitlist)
tree_set.add(i);
System.out.println( "TreeSet from List : "
+ tree_set);
}
}
|
OutputFruit List : [Mango, Apple, Grape, Papaya]
TreeSet from List : [Apple, Grape, Mango, Papaya]
Time Complexity: O(N)
Approach 3 :
1. Initialize and Declare the List object with inputs.
2. Now, Create the TreeSet object.
3. Collections.addAll() is used to add all elements from one object to another object.
4. Print the TreeSet.
Java
import java.util.*;
class GFG {
public static void main(String[] args) {
List<String> fruitlist = new ArrayList<String>();
fruitlist.add( "Mango" );
fruitlist.add( "Apple" );
fruitlist.add( "Grape" );
fruitlist.add( "Papaya" );
System.out.println( "Fruit List : " + fruitlist);
TreeSet<String> tree_set = new TreeSet<String>();
tree_set.addAll(fruitlist);
System.out.println( "TreeSet from List : "
+ tree_set);
}
}
|
Output :
Fruit List : [Mango, Apple, Grape, Papaya]
TreeSet from List : [Apple, Grape, Mango,Papaya]