Most concise way to convert a Set<T> to a List<T>
List<String> list = new ArrayList<String>(listOfTopicAuthors);
List<String> l = new ArrayList<String>(listOfTopicAuthors);
Considering that we have Set<String> stringSet
we can use following:
Plain Java
List<String> strList = new ArrayList<>(stringSet);
Guava
List<String> strList = Lists.newArrayList(stringSet);
Apache Commons
List<String> strList = new ArrayList<>();
CollectionUtils.addAll(strList, stringSet);
Java 10 (Unmodifiable List)
List<String> strList = List.copyOf(stringSet);
List<String> strList = stringSet.stream().collect(Collectors.toUnmodifiableList());
Java 8 (Modifiable Lists)
import static java.util.stream.Collectors.*;
List<String> stringList1 = stringSet.stream().collect(toList());
As per the doc for the method toList()
There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned; if more control over the returned List is required, use toCollection(Supplier).
So if we need a specific implementation e.g. ArrayList
we can get it this way:
List<String> stringList2 = stringSet.stream().
collect(toCollection(ArrayList::new));
Java 8 (Unmodifiable Lists)
We can make use of Collections::unmodifiableList
method and wrap the list returned in previous examples. We can also write our own custom method as:
class ImmutableCollector {
public static <T> Collector<T, List<T>, List<T>> toImmutableList(Supplier<List<T>> supplier) {
return Collector.of( supplier, List::add, (left, right) -> {
left.addAll(right);
return left;
}, Collections::unmodifiableList);
}
}
And then use it as:
List<String> stringList3 = stringSet.stream()
.collect(ImmutableCollector.toImmutableList(ArrayList::new));
Another possibility is to make use of collectingAndThen
method which allows some final transformation to be done before returning result:
List<String> stringList4 = stringSet.stream().collect(collectingAndThen(
toCollection(ArrayList::new),Collections::unmodifiableList));
One point to note is that the method Collections::unmodifiableList
returns an unmodifiable view of the specified list, as per doc. An unmodifiable view collection is a collection that is unmodifiable and is also a view onto a backing collection. Note that changes to the backing collection might still be possible, and if they occur, they are visible through the unmodifiable view. But the collector method Collectors.unmodifiableList
returns truly immutable list in Java 10.