Dylan Knowles Dylan Knowles - 1 month ago 8
Java Question

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? */
}

Answer

Alternately, you can use flatMap:

Stream<Region> = 
    Stream.of(usaRegions, canadaRegions, mexicoRegions)
          .flatMap(Collection::stream);
Comments