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?
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());
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
);
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.