gpt4 book ai didi

java - Java 8 是否缺少处理可变流的 Stream.concat?

转载 作者:IT老高 更新时间:2023-10-28 20:34:50 34 4
gpt4 key购买 nike

目前我们有以下Stream.concat在 Java 8 中:

public static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b);

我很惊讶为什么没有版本采用 Stream<? extends T> 的可变参数?

目前我的代码如下:

Stream<Integer> resultStream = Stream.concat(stream1, Stream.concat(stream2, Stream.of(element)))
.filter(x -> x != 0)
.filter(x -> x != 1)
.filter(x -> x != 2);

如果此签名的可变参数可用:

public static <T> Stream<T> concat(Stream<? extends T>... streams);

然后我可以更清楚地写成:

Stream<Integer> resultStream = Stream.concat(
stream1,
stream2,
Stream.of(element)
)
.filter(x -> x != 0)
.filter(x -> x != 1)
.filter(x -> x != 2);

无各种嵌套Stream.concat来电。

还是有其他原因没有提供?
我想不出这样的原因,因为我们现在最终还是做了可变参数调用的工作。

最佳答案

flatMap吧:

public static void main(final String[] args) throws Exception {
final Stream<String> stream1 = /*some stream*/
final Stream<String> stream2 = /*some stream*/
final Stream<String> stream3 = /*some stream*/
final Stream<String> stream4 = /*some stream*/
final Stream<String> stream5 = /*some stream*/

final Stream<String> stream = Stream.of(stream1, stream2, stream3, stream4, stream5).flatMap(Function.identity());
}

在你的例子中:

Stream<Integer> resultStream = Stream.of(stream1, stream2, Stream.of(element))
.flatMap(identity())
.filter(x -> x != 0)
.filter(x -> x != 1)
.filter(x -> x != 2);

关于java - Java 8 是否缺少处理可变流的 Stream.concat?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22743425/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com