Java 8 是否缺少一个 Stream.concat 来处理一堆流?

2022-08-31 17:13:44

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

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

我很惊讶为什么没有版本采取一个 varargs 的 ?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);

如果此签名的 varargs 可用:

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

还是没有其他原因没有提供?
我想不出这样的理由,因为我们现在无论如何都会做一个varargs电话的工作。


答案 1

就这样: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);

答案 2

@RohitJain链接的线程中的消息中收集:

Stream.of(s1, s2, s3, ...)
  /* .parallel() if you want*/
  .reduce(Stream::concat)
  .orElseGet(Stream::empty);

推荐