Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 329
Andrew Mairose Avatar asked Jul 29 '15 16:07

Andrew Mairose


People also ask

How do I add two collections in Java 8?

If you need to combine more than two Streams, you can invoke the concat() method again from within the original invocation: Stream<String> combinedStream = Stream. concat( Stream. concat(collectionA.

How do you combine streams in Java?

concat() in Java. Stream. concat() method creates a concatenated stream in which the elements are all the elements of the first stream followed by all the elements of the second stream. The resulting stream is ordered if both of the input streams are ordered, and parallel if either of the input streams is parallel.

How do I combine Iterables?

Concatenate Iterables using concat Method The Iterables class provides concat method that accepts n number of Iterable instances and returns a new Iterable instance having all elements concatenated. Note that this method creates a new instance; hence we can pass Immutable Lists.


1 Answers

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()); 
like image 172
rgettman Avatar answered Oct 02 '22 18:10

rgettman