How to Convert Array to TreeSet in Java

In this post, I will be sharing how to convert Array to TreeSet in Java. I have already shared what is the difference between HashSet and TreeSet in Java. Also, in this post we will write a program on how to convert Array to TreeSet in Java.

The easiest way to achieve our goal of converting Array to TreeSet is by using TreeSet constructor.

First, we will convert Array into list using Arrays.asList() method. Then, we will pass the list as an argument to the TreeSet constructor.

Read Also: How TreeSet works internally in Java

Program to Convert Integer Array to TreeSet in Java


import java.util.*;

 public class ArrayToTreeSet {
    public static void main(String args[]) {
        
    Integer[] num = {7,34,45,23,38,56,21};
    /*First we convert an Array to List using
      Arrays.asList(), then pass the list as an
      argument to the constructor of TreeSet */
    List<Integer> list = Arrays.asList(num);
    Set<Integer> set = new TreeSet<Integer>(list);
    // Show Set elements
    System.out.println("The Set elements are :");
    for(Integer var : set)
        System.out.println(var);
  }
}

Output:


The Set elements are :
7
21
23
34
38
45
56


Program to Convert String Array to TreeSet in Java


import java.util.*;

public class ArrayToTreeSet2 {
    public static void main(String args[]) {
      String[] arr = {"Alive", "is" , "Awesome"};
      // Converting Array to list
      List<String> list = Arrays.asList(arr);
      // Converting list to TreeSet
      TreeSet<String> treeset = new TreeSet<>(list);
      // Iterating and Printing TreeSet elements
      for(String str : treeset)
      {
        System.out.println(str);  
      }    
    }
}


Output:
Alive
Awesome
is


That's all for today. Please mention in the comments if you have any questions related to how to convert Array to TreeSet in Java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry