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? */
}
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.
With three streams we could write Stream. concat(Stream. concat(a, b), c) .
Alternately, you can use flatMap:
Stream<Region> =
Stream.of(usaRegions, canadaRegions, mexicoRegions)
.flatMap(Collection::stream);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With