I'm trying to use Java 8 Lambda/Stream API for modeling a simple producer/consumer system, just like:
Stream<Sample> samplesFlow = Stream.generate(new SampleSupplier());
samplesFlow.forEach(new SampleConsumer());
I realized that "scale" to several consumers was pretty simple:
samplesFlow
.peek(new SampleConsumer1())
.peek(new SampleConsumer2())
.forEach(new SampleConsumer3());
But what about adding new producers to the system? Is there some idiomatic or "elegant" way to generate a Stream from several infinite Suppliers?? Like:
Stream.generate(new SampleSupplier1(),new SampleSupplier2()); // made it up
Each supplier simulate a network listener getting data from a remote source.
Thanks in advance!
You didn’t specify how you want to combine the supplied values.
If you want to have the values alternating, a solution would be:
Stream.generate(supplier1).flatMap(x->Stream.of(x, supplier2.get()))
If you want to have some kind of pair, you can use
Stream.generate(()->new Pair<>(supplier1.get(), supplier2.get()))
though it is up to you to write the Pair
class as the jdk does not offer such a class. (You could abuse AbstractMap.SimpleEntry
but that’s rather nasty).
If you have a finite Stream
you can use Stream.concat
to create a stream which will process all items of the first stream before the items of the second, however, streams created using a Supplier
are infinite by default so you have to use limit
on the first stream before you can concat it to another stream, so it’s not a general solution.
If you want to query each Supplier
exactly once, you can use
Stream.of(supplier1, supplier2).map(Supplier::get)
though, of course, if you don’t need lazy evaluation of the Supplier
s, a
Stream.of(supplier1.get(), supplier2.get())
would do as well.
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