How to Convert Array to TreeSet in Java

I have already shared what is the difference between HashSet and TreeSet in java. In this post we will write a program on how to convert Array to TreeSet in java. First we will convert Array to TreeSet into list using Arrays.asList() method.Then, we will pass the list as an argument to the TreeSet constructor.

Program to Convert 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



About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry