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.
A stream can be converted to a list using its
Collectorwhich can be obtained using
// 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() 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.
Java 16 introduced
toList()method which can directly convert a stream to list without using
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
1. Of type
java.util.List and not an
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
The returned List is unmodifiable; calls to any mutator method will always cause
UnsupportedOperationExceptionto be thrown.
null elements in the stream.
Stream.toList() consumes lesser memory and should be preferred when stream size is known in advance and the resultant list need not be modified.