10

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? */
}
Jonik
  • 80,077
  • 70
  • 264
  • 372
Dylan Knowles
  • 2,726
  • 1
  • 26
  • 52
  • 6
    Yea its `java.util.stream.Stream.concat`. See http://stackoverflow.com/questions/22740464/adding-two-java-8-streams-or-an-extra-element-to-a-stream – ug_ Nov 05 '15 at 02:45
  • 1
    Neat -- I didn't realize that `concat` existed! Thanks! – Dylan Knowles Nov 05 '15 at 02:57

1 Answers1

17

Alternately, you can use flatMap:

Stream<Region> = 
    Stream.of(usaRegions, canadaRegions, mexicoRegions)
          .flatMap(Collection::stream);
Brian Goetz
  • 90,105
  • 23
  • 150
  • 161