Convert Set to List in Java
This post will discuss how to convert a set to a list in Java.
1. Naive solution
A naive solution is to create an empty list and add every element of the specified set to it.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Generic method to convert a set to a list public static <T> List<T> convertToList(Set<T> set) { // create an empty list List<T> items = new ArrayList<>(); // push each set element into the list for (T e: set) { items.add(e); } // return the list return items; } |
2. Using Constructor
We can use the ArrayList constructor, which can take another collection object to construct a new list containing all elements of the specified set.
|
1 2 3 4 |
// Generic method to convert a set to a list public static <T> List<T> convertToList(Set<T> set) { return new ArrayList<>(set); } |
3. Java 8 and above
In Java 8, we can use the Stream 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.
|
1 2 3 4 |
// Generic method to convert a set to a list public static <T> List<T> convertToList(Set<T> set) { return set.stream().collect(Collectors.toList()); } |
Since Collectors.toList() doesn’t guarantee on the type of the List returned, we can use Collectors.toCollection() to specify the desired Collection:
|
1 2 3 4 |
// Generic method to convert a set to `ArrayList` public static <T> List<T> convertToList(T[] arr) { return set.stream().collect(Collectors.toCollection(ArrayList::new)); } |
4. Using Guava Library
We can also use 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.
|
1 2 3 4 |
// Generic method to convert a set to a list public static <T> List<T> convertToList(Set<T> set) { return Lists.newArrayList(set); } |
2. We can also use ImmutableList.copyOf that returns an immutable list containing the specified set elements. This should be preferred when mutability is not needed.
|
1 2 3 4 |
// Generic method to convert a set to a list public static <T> List<T> convertToList(Set<T> set) { return ImmutableList.copyOf(set); } |
That’s all about converting Set to List in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)