Convert stream to list

In this article, we will look at different ways to convert java 8 streams to list. The article will also cover Stream.toList() method introduced in java 16.

1. Stream to List with collect()
A stream can be converted to a list using its collect() method.
collect() accepts a Collector which can be obtained using Collectors.toList() method. Example,

// create a stream of integers
Stream<Integer> stream = Stream.of(1, 2, 3, 4);
// convert stream to list
List<Integer> list = stream.collect(Collectors.toList());

Following are some important points regarding the list returned by this method.

1. The list is an instance of java ArrayList.
2. The list is modifiable. That is, you can add or remove elements from it.
3. This method allows null elements to be added to the list.
2. Stream to list with filter()
Instead of calling collect() on stream, you can call filter().
filter() takes a Predicate as argument, which is a boolean condition.
filter() is invoked on each element of the stream and the element which satisfied the supplied predicate is added to the resultant collection.

To convert the filtered elements to a list, use collect() method with Collectors.toList() as argument. Example,

// create a stream of integers 
Stream<Integer> stream = Stream.of(1, 2, 3, 4); 
// convert stream to list 
List<Integer> list = stream.filter(n -> n < 5).collect(Collectors.toList());

Resultant list will have elements which are lesser than 5 as per the supplied predicate.
This method is used to filter out elements from a stream.

3. Java 16 Stream.toList()
Java 16 introduced toList() method which can directly convert a stream to list without using collect() or filter() operations.

toList() is a default interface method which can be directly called on a stream. Example,

// create a stream of integers 
Stream<Integer> stream = Stream.of(1, 2, 3, 4); 
// convert stream to list 
List<Integer> list = stream.toList();

The list returned by toList():

1. Of type java.util.List and not an ArrayList.
2. Is unmodifiable. That is, you can not add or remove elements from it.
Trying to do so would result in

Exception in thread “main” java.lang.UnsupportedOperationException

As per java docs for toList(),

The returned List is unmodifiable; calls to any mutator method will always cause UnsupportedOperationException to be thrown.

3. Allows null elements in the stream.
4. Stream.toList() consumes lesser memory and should be preferred when stream size is known in advance and the resultant list need not be modified.

That is all on converting a stream to list in java. Hope the article was useful.