Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the easiest way to combine multiple collections into a stream in Java?

Suppose I have multiple collections that I'd like to handle as a single stream. What's the easiest way to do this? Is there a utility class that can do this for me, or do I have to roll something myself?

In case my question isn't clear, this is essentially what I'm trying to do:

Collection<Region> usaRegions;
Collection<Region> canadaRegions;
Collection<Region> mexicoRegions;
Stream<Region> northAmericanRegions = collect(usaRegions, canadaRegions, mexicoRegions);

public Stream<T> collect(T...) {
     /* What goes here? */
}
like image 984
Dylan Knowles Avatar asked Nov 05 '15 02:11

Dylan Knowles


People also ask

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 concatenate 3 streams?

With three streams we could write Stream. concat(Stream. concat(a, b), c) .


1 Answers

Alternately, you can use flatMap:

Stream<Region> = 
    Stream.of(usaRegions, canadaRegions, mexicoRegions)
          .flatMap(Collection::stream);
like image 199
Brian Goetz Avatar answered Nov 15 '22 20:11

Brian Goetz