Combine stream of Collections into one Collection - Java 8

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.


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
);

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());