Skip to content

Convert TreeSet to ArrayList (List, LinkedList) in Java Example

This example shows how to convert TreeSet to ArrayList (or List or LinkedList) in Java. This example also shows how to convert TreeSet to List using the constructor and addAll method.

How to convert TreeSet to ArrayList (or TreeSet to List or LinkedList) in Java?

There are a couple of ways using which we can convert TreeSet object to an object of ArrayList as given below.

1. Using ArrayList constructor

The ArrayList in Java provides a constructor that accepts a collection object.

It creates a new ArrayList object containing all the elements of the specified collection object. Since the Collection interface is a parent interface of the Set interface, we can pass the TreeSet object in this constructor.

Output

As we can see from the output, the TreeSet class automatically sorts the elements according to the element’s natural order. So when we converted the TreeSet to an ArrayList object, we got the string elements sorted alphabetically (i.e. natural order of the String type).

2. Using the ArrayList addAll method

Instead of using the copy constructor given above, we can also use the addAll method of the ArrayList class.

The addAll method adds all elements of the specified collection object to this List object. Just like the constructor, the addAll method also accepts the TreeSet object as a collection object.

Output

As opposed to the copy constructor approach, this approach is a two-step process, first, we need to create an empty List object and then we need to add all elements of the TreeSet object to the List object using the addAll method.

We can also convert TreeSet to LinkedList in Java using any of the above given approaches. We just need to replace the ArrayList constructor with the LinkedList constructor.

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

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

References:
Java 8 TreeSet

About the author

Leave a Reply

Your email address will not be published.