Convert Set to List in Java

In this post, we will see how to convert set to list in Java.


1. Naive solution

Naive solution would be to create an empty list and add every element of the specified set to it.


2. Constructor

We can make use of ArrayList constructor which can take another collection object to construct a new list containing all elements of the specified set.


3. Java 8

In Java 8, we can use Stream API to convert a set to a list by converting the specified set to a sequential Stream using and using a Collector to accumulate the input elements into a new List.

Since Collectors.toList() doesn’t guarantee on the type of the List returned, we can use Collectors.toCollection() to specify the desired Collection –


4. Guava Library

We can also use the Guava API to convert a set to a list.

1. Lists.newArrayList() creates a mutable ArrayList instance containing the elements of the specified set. This method is preferred if we need to add or remove elements later or some of the elements can be null.

2. We can also use ImmutableList.copyOf that returns an immutable list containing the elements of the specified set. This should be preferred when mutability is not needed.

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of