So I have a
Stream<Collection<Long>> that I obtain by doing a series of transformations on another stream.
What I need to do is collect the
Stream<Collection<Long>> into one
I could collect them all into a list like this:
<Stream<Collection<Long>> streamOfCollections = /* get the stream */; List<Collection<Long>> listOfCollections = streamOfCollections.collect(Collectors.toList());
And then I could iterate through that list of collections to combine them into one.
However, I imagine there must be a simple way to combine the stream of collections into one
Collection<Long> using a
.collect(). I just can’t think of how to do it. Any ideas?
This functionality can be achieved with a call to the
flatMap method on the stream, which takes a
Function that maps the
Stream item to another
Stream on which you can collect.
flatMap method converts the
Stream<Collection<Long>> to a
collect collects them into a
Collection<Long> longs = streamOfCollections .flatMap( coll -> coll.stream()) .collect(Collectors.toList());