reduce()方法如何与Java 8中的并行流一起使用? [英] How does reduce() method work with parallel streams in Java 8?

查看:403
本文介绍了reduce()方法如何与Java 8中的并行流一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了解reduce()方法如何与并行流完全兼容,并且我不理解为什么以下代码不返回这些字符串的串联.

I try to understand how reduce() method works exactly with parallel streams and I don't understand why the following code do not return the concatenation of these strings.

这是代码:

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

    }
}

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

The code works only with sequential streams, but with parallel streams it doesn't return the concatenation. The output is different every time. Can someone explain me what's happening there?

推荐答案

问题是您使用 Streams:Reduction 中了解差异.与reduce方法(在处理元素时总是会创建新值)不同,collect方法会修改或变异现有值.

The problem is you use Stream::reduce for Mutable reduction, which has been Stream::collect specifically designed for. It can be either used for the safe parallel storing. Read about the differences also at official Oracle documentation Streams: Reduction. Unlike the reduce method, which always creates new value when it processes an element, the collect method modifies or mutates an existing value.

从JavaDoc中注意到这两种方法之间的区别:

Notice the differences between both methods from their JavaDoc:

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