gpt4 book ai didi

java - 在 Java 8 中,reduce() 方法如何处理并行流?

转载 作者:行者123 更新时间:2023-12-01 14:14:19 25 4
gpt4 key购买 nike

我试着理解 reduce()方法完全适用于并行流,我不明白为什么以下代码不返回这些字符串的串联。

这是代码:

public class App {

public static void main(String[] args) {
String[] grades = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"};

StringBuilder concat = Arrays.stream(grades).parallel()
.reduce(new StringBuilder(),
(sb, s) -> sb.append(s),
(sb1, sb2) -> sb1.append(sb2));

System.out.println(concat);

}
}

该代码仅适用于顺序流,但对于并行流,它不会返回串联。每次输出都不一样。有人能解释一下那里发生了什么吗?

最佳答案

问题是你用了 Stream::reduce Mutable reduction , 已 Stream::collect 专为。它既可以用于安全的并行存储。也可以在 Oracle 官方文档 Streams: Reduction 中了解这些差异。 .与在处理元素时总是创建新值的 reduce 方法不同,collect 方法修改或改变现有值。

请注意 JavaDoc 中两种方法之间的差异:

  • reduce(U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner) :

    Performs a reduction on the elements of this stream, using the provided identity, accumulation and combining functions.

  • collect(Supplier<R> supplier, BiConsumer<R,? super T> accumulator, BiConsumer<R,R> combiner) :

    Performs a mutable reduction operation on the elements of this stream.


  • 因此,我建议您执行以下操作:
    StringBuilder concat = Arrays.stream(grades)
    .parallel()
    .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append);

    关于java - 在 Java 8 中,reduce() 方法如何处理并行流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56023452/

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