Convert Array to TreeSet in Java Example

This example shows how to convert an array to TreeSet in Java. This example also shows how to convert array to TreeSet using constructor, addAll method, Collections class, for loop, and Java 8 stream.

How to convert an Array to TreeSet in Java?

There are several ways using which we can convert an array to TreeSet object as given below. I am going to use an Integer array for the purpose of this example.

1. Using for loop

The simplest way is to loop through an array and add elements to the TreeSet object one by one as given below.


2. Using TreeSet constructor

We can use the TreeSet constructor that accepts a collection object, but for that, we need to convert an array to a collection first. We can use the asList method of the Arrays class that returns a List wrapper around an array to do that.


3. Using the TreeSet addAll method

The addAll method of the TreeSet class adds all elements of the specified collection object to the set object. We are going to convert array to a List using the same asList method of the Arrays class and then use the addAll method.


4. Using Collections addAll method

Instead of the addAll method of the TreeSet class, we can also use the addAll method of the Collections class as given below.


5. Using Apache Commons CollectionUtils class

If you are using the Apache Commons library, we can use the addAll method of the CollectionUtils class to convert an array to a TreeSet object.


6. Using Java 8 Stream

If you are using Java version 8 or later, you can use the Java stream to convert an array to a set as given below.


As we can see from the output, the TreeSet class automatically sorts the array elements in their natural order i.e. ascending order for the type Integer. Also, the original array contained 6 elements, but when we converted it to an array, we got only 5 elements.

It is because the TreeSet is an implementation of the Set interface that does not allow duplicate elements hence the last element “2” was not added to the TreeSet as it was duplicated.

Please also visit how to convert TreeSet to an array example to know more.

This example is a part of the TreeSet in Java Tutorial with Examples.

Please let me know your views in the comments section below.

Java 8 TreeSet

About the author



My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *

Online Shopping