Reputation: 10995
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?
Upvotes: 39
Views: 24114
Reputation: 11
You don't need to specify classes when not needed. A better solution is:
Collection<Long> longs = streamOfCollections.collect(
ArrayList::new,
Collection::addAll,
Collection::addAll
);
Say, you don't need an ArrayList but need a HashSet, then you also need to edit only one line.
Upvotes: 1
Reputation: 95588
You could do this by using collect
and providing a supplier (the ArrayList::new
part):
Collection<Long> longs = streamOfCollections.collect(
ArrayList::new,
ArrayList::addAll,
ArrayList::addAll
);
Upvotes: 15
Reputation: 178333
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());
Upvotes: 71