在归约运算中永远不会调用合并器(但是强制性的) [英] Combiner never gets called in reduction operation (but is mandatory)

查看:65
本文介绍了在归约运算中永远不会调用合并器(但是强制性的)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出reduce流操作中的累加器和组合器.

I am trying to figure out what accumulator and combiner do in reduce stream operation.

    List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));

    int result = users.stream()
            .reduce(0,
                    (partialAgeResult, user) -> {
                        // accumulator is called twice
                        System.out.println(MessageFormat.format("partialAgeResult {0}, user {1}", partialAgeResult, user));
                        return partialAgeResult + user.getAge();
                    },
                    (integer, integer2) -> {
                        // combiner is never called
                        System.out.println(MessageFormat.format("integer {0}, integer2 {1}", integer, integer2));
                        return integer * integer2;
                    });

    System.out.println(MessageFormat.format("Result is {0}", result)); 

我注意到合并器从未执行过,结果是65. 如果我使用users.parallelStream(),则组合器执行一次,结果为1050.

I notice that the combiner is never executed, and the result is 65. If I use users.parallelStream() then the combiner is executed once and the result is 1050.

为什么streamparallelStream产生不同的结果?我看不到并行执行此操作的任何副作用.

Why stream and parallelStream yield different results? I don't see any side-effects of executing this in parallel.

简单流版本中组合器的作用是什么?

What is the purpose of the combiner in the simple stream version?

推荐答案

问题在这里.您正在乘法而不是在合并器中加法.

The problem is here. You are multiplying and not adding in your combiner.

 (integer, integer2) -> {
                        // combiner is never called
                        System.out.println(MessageFormat.format("integer {0}, integer2 {1}", integer, integer2));
                        return integer * integer2; //<----- Should be addition
                    });

组合器用于适当地组合并行操作的各个部分,因为这些操作可以在单独的片段"上独立执行.原始流的大小.

The combiner is used to appropriately combine various parts of a parallel operation as these operations can perform independently on individual "pieces" of the original stream.

一个简单的示例是对元素列表求和.在并行操作中,您可能会有各种部分和,因此您需要对组合器中的部分和求和才能获得总和(这是一个很好的练习,您可以自己尝试看看).

A simple example would be summing a list of elements. You could have a variety of partial sums in a parallel operation, so you need to sum the partial sums in the combiner to get the total sum (a good exercise for you to try and see for yourself).

这篇关于在归约运算中永远不会调用合并器(但是强制性的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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