How to Get a List from a Stream in Java
Suppose we have list of integers called src
that we want to convert to a stream and filter.
src.stream().filter(num -> num > 2)
Let’s say we want to store the result in this dst
list.
List<Integer> dst;
Get list from stream with Collectors.toList()
We can use Collectors.toList()
to retrieve a list from a stream.
dst = src.stream()
.filter(num -> num > 2)
.collect(Collectors.toList());
The only issue with Collectors.toList()
can be seen in the Java documentation on Collectors
:
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)
.
Get list from stream with Collectors.toCollection()
If we want a particular List implementation (i.e. ArrayList
, LinkedList
, etc.), then we can use Collectors.toCollection()
.
dst = src.stream()
.filter(num -> num > 2)
.collect(Collectors.toCollection(ArrayList::new));