Java 8 Stream - Reduce function's combiner not

2020-02-13 04:29发布

I am using a simple reduce method with three arguments viz. identity, accumulator and combiner. Here is my code...

Integer ageSumComb = persons
            .stream()
            .reduce(0,
                (sum, p) -> {
                    System.out.println("Accumulator: Sum= "+ sum + " Person= " + p);
                    return sum += p.age;
                },
                (sum1, sum2) -> {
                    System.out.format("Combiner: Sum1= " + sum1 + " Sum2= "+ sum2);
                    return sum1 + sum2;

But what is happening is the Combiner is not getting executed. I am not getting the reason behind this. Here is my output..

Accumulator: Sum= 0 Person= Max
Accumulator: Sum= 18 Person= Peter
Accumulator: Sum= 41 Person= Pamela
Accumulator: Sum= 64 Person= David
Accumulator: Sum= 76 Person= Pam

However, There was no compilation error and no exception and my output is exactly right, the same what i had expected. But did not get why the combiner not executed.

2条回答
时光不老,我们不散
2楼-- · 2020-02-13 04:35

You need to use parallelStream instead of stream if you are going to use combiner

查看更多
该账号已被封号
3楼-- · 2020-02-13 04:50

Combiner gets executed only for a parallel stream.

查看更多
登录 后发表回答