Retrieve a List from a Stream in Java

Retrieving a List from a Stream in Java 8

1. Overview

In this article, we will learn to retrieve a List from a Stream in Java.

2. Retrieve a List from a Stream in Java

Over time, Java introduced various APIs in its subsequent releases to convert a stream to a list.

2.1. Use Collectors.toList()

It collects the input stream elements into a new List. This doesn’t guarantee that returned list in mutable or type safe. You can consider using Collectors.toCollection method to get a mutable list.

List<String> tempList = Arrays.asList("John", "Mike", "Chris", "Kevin");
List<String> destList = tempList.stream()
    .filter(name -> name.startsWith("J"))
    .collect(Collectors.toList());

2.2. Use Collectors.toUnmodifiableList()

To create an immutable list, then use Collectors.toUnmodifiableList() introduced in Java 10. This method does not allow any null values and will throw NullPointerException if we present it with a null value.

List<String> tempList = Arrays.asList("John", "Mike", "Chris", "Kevin");
ImmutableList<String> destList = tempList.stream()
    .filter(name -> name.startsWith("J"))
    .collect(Collectors.toUnmodifiableList());

2.2. Use Collectors.toCollection

The Collectors.toList doesn’t guarantee the type, mutability, ability to serialize, or thread-safety of the returned list. So use toCollection(Supplier collectionFactory) to control over the returned List.

It also guarantees to return mutable list.

The collection factory provides a new empty Collection into which the results would be inserted. This method returns a Collector that gathers the input stream elements into the empty Collection.

For example, the following code returns an ArrayList as result which is mutable. The Supplier or collection factory here is ArrayList::new which would create an empty ArrayList and the collector gathers the stream elements into this empty ArrayList.

List<String> tempList = Arrays.asList("John", "Mike", "Chris", "Kevin");
List<String> destList = tempList.stream()
    .filter(name -> name.startsWith("J"))
    .collect(Collectors.toCollection(ArrayList::new));

2.3. Use Stream.toList() - Java 16

You can use the method Stream.toList() available in Java 16. This allows null values in the stream.

This method provides a List implementation that is immutable (type ImmutableCollections.ListN that cannot be added or sorted) similar to that provided by List.of(). However, you can use Stream.collect(Collectors.toList()) for a mutable (which can be changed and sorted) ArrayList.

List<String> destList = tempList
    .stream()
    .filter(name -> name.startsWith("J"))
    .toList();

3. Conclusion

To sum up, we have learned to convert a Stream to List in Java.

Leave a Reply

Your email address will not be published. Required fields are marked *