Retrieving a List from a java.util.stream.Stream in Java 8
I like to use a util method that returns a collector for ArrayList
when that is what I want.
I think the solution using Collectors.toCollection(ArrayList::new)
is a little too noisy for such a common operation.
Example:
ArrayList<Long> result = sourceLongList.stream()
.filter(l -> l > 100)
.collect(toArrayList());
public static <T> Collector<T, ?, ArrayList<T>> toArrayList() {
return Collectors.toCollection(ArrayList::new);
}
With this answer I also want to demonstrate how simple it is to create and use custom collectors, which is very useful generally.
What you are doing may be the simplest way, provided your stream stays sequential—otherwise you will have to put a call to sequential() before forEach
.
[later edit: the reason the call to sequential() is necessary is that the code as it stands (forEach(targetLongList::add)
) would be racy if the stream was parallel. Even then, it will not achieve the effect intended, as forEach
is explicitly nondeterministic—even in a sequential stream the order of element processing is not guaranteed. You would have to use forEachOrdered
to ensure correct ordering. The intention of the Stream API designers is that you will use collector in this situation, as below.]
An alternative is
targetLongList = sourceLongList.stream()
.filter(l -> l > 100)
.collect(Collectors.toList());
Updated:
Another approach is to use Collectors.toList
:
targetLongList =
sourceLongList.stream().
filter(l -> l > 100).
collect(Collectors.toList());
Previous Solution:
Another approach is to use Collectors.toCollection
:
targetLongList =
sourceLongList.stream().
filter(l -> l > 100).
collect(Collectors.toCollection(ArrayList::new));