Combine stream of Collections into one Collection – Java 8

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 Collection<Long>.

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 .map() or .collect(). I just can’t think of how to do it. Any ideas?

Answer

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.

Here, the flatMap method converts the Stream<Collection<Long>> to a Stream<Long>, and collect collects them into a Collection<Long>.

Collection<Long> longs = streamOfCollections
    .flatMap( coll -> coll.stream())
    .collect(Collectors.toList());

Leave a Reply

Your email address will not be published. Required fields are marked *