从多个供应商生成一条流 [英] Generate one Stream from multiple Suppliers

查看:53
本文介绍了从多个供应商生成一条流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Java 8 Lambda/Stream API来为简单的生产者/消费者系统建模,就像:

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.

提前谢谢!

推荐答案

您未指定要如何组合提供的值.

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()))

尽管您可以编写 Pair 类,因为jdk不提供此类.(您可能会滥用 AbstractMap.SimpleEntry ,但这很讨厌).

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).

如果您有一个有限的 Stream ,则可以使用

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)

当然,如果您不需要对 Supplier s进行懒惰的评估,则可以

though, of course, if you don’t need lazy evaluation of the Suppliers, a

Stream.of(supplier1.get(), supplier2.get())

也会这样做.

这篇关于从多个供应商生成一条流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆