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 Set.stream() 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.

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Get great deals at Amazon




Leave a Reply

avatar
  Subscribe  
Notify of