更新时间:2023-11-16 23:35:58
您未指定要如何组合提供的值.
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
,则可以使用 limit
另一个流,所以这不是一个通用的解决方案.
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 Supplier
s, a
Stream.of(supplier1.get(), supplier2.get())
也会这样做.