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?
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.
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.
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With