Open In App

How to Convert an ArrayList or an Array into a TreeSet in Java?

In Java, ArrayList allows random access because it works like an array. It means you can access any element by its index in O(1) at any time. A TreeSet is a sorted set implementation of the Set interface based on a TreeMap. It provides log(n) time complexity for basic operations like add, remove, and contains due to its tree implementation.

In this article, we will learn how to convert an ArrayList or an Array into a TreeSet in Java.



Syntax to convert an ArrayList into a TreeSet:

ArrayList<Type> arrayList =  (initialize and add elements to the ArrayList)
TreeSet<Type> treeSet = new TreeSet<>(arrayList);

Program to convert an ArrayList to a TreeSet in Java

Implementation:

Below is the implementation to convert an ArrayList to a TreeSet.




// Java Program to convert an ArrayList to a TreeSet in Java
import java.util.ArrayList;
import java.util.TreeSet;
  
public class ArrayListToTreeSetExample {
    public static void main(String[] args) {
       // Create an ArrayList
        ArrayList<String> courseList = new ArrayList<>();
        courseList.add("C++");
        courseList.add("Java");
        courseList.add("Python");
        courseList.add("Java"); // Duplicate entry
  
        // Create a TreeSet
        TreeSet<String> courseSet = new TreeSet<>();
  
        // Add elements from ArrayList to TreeSet
        courseSet.addAll(courseList);
  
        // Print the elements
        System.out.println("Elements of CourseList: " + courseList);
        System.out.println("Elements of CourseSet: " + courseSet);
    }
}

Output

Elements of CourseList: [C++, Java, Python, Java]
Elements of CourseSet: [C++, Java, Python]

Explanation of the Program:

Syntax to convert an Array into a TreeSet:

T[] array = {array elements}; 
// Convert array to TreeSet
TreeSet<T> treeSet = new TreeSet<>(Arrays.asList(array));

Program to convert an Array to a TreeSet in Java

Implementation:

Below is the implementation to convert an Array to a TreeSet.




// Java Program to convert an Array to a TreeSet 
import java.util.Arrays;
import java.util.TreeSet;
  
public class ArrayToTreeSetExample {
    public static void main(String[] args) {
        // Create an array
        String[] course = {"Java", "Python", "Python", "C++"};
  
        // Create a TreeSet
        TreeSet<String> courseSet = new TreeSet<>();
  
        // Add elements from array to TreeSet
        courseSet.addAll(Arrays.asList(course));
  
        // Print the elements 
        System.out.println("Elements of Course Array: " + Arrays.toString(course));
        System.out.println("Elements of Course Set: " + courseSet);
    }
}

Output
Elements of Course Array: [Java, Python, Python, C++]
Elements of Course Set: [C++, Java, Python]

Explanation of the Program:


Article Tags :