Understanding Java Stream reduce - parallel vs series

陌路散爱 提交于 2021-01-29 22:20:46

问题


I have Java code which uses lambdas and streams to find the average of a list of integers. It uses Stream.reduce(...) to find the sum of integers and then calculates average. The code works correctly even when I remove the parallel() call. Can someone explain why ? More questions after the code.

import java.util.Arrays;
import java.util.List;

public class Temp {
    public static void main(String [] args){
        //For example, consider a list of a *series* of numbers in increasing order.
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
        int n = numbers.get(numbers.size()-1);//n = 6 is the number of numbers in list.

        double expectedSum = (n * (n + 1))/2;//By mathematical formula for increasing series.

        Double sum = numbers
                //Take a stream of integers.
                .stream()
                //Split the stream into mini streams and calculate sum of each of mini stream.
                .parallel()
                //Reduce all the numbers in a stream to their sum.
                .reduce(
                        //start with a partial sum of 0.
                0.0,
                //For a stream, calculate the sum of all the numbers.
                (partialSum, nextNumber) -> partialSum + (double) nextNumber,
                //Add the sums of each mini stream.
                (onePartialSum, anotherPartialSum) -> (onePartialSum + anotherPartialSum)
        );

        System.out.println("Sum : expected value = " + expectedSum + ", actual value = " + sum);

        double expectedAverage = expectedSum/numbers.size();
        double average = sum/numbers.size();

        System.out.println("Average : expected value = " + expectedAverage + ", actual value = " + average);

    }
}

Output:

Sum : expected value = 21.0, actual value = 21.0
Average : expected value = 3.5, actual value = 3.5

Consider the code below for the function which is a BinaryOperator<U> combiner :

(onePartialSum, anotherPartialSum) -> (onePartialSum + anotherPartialSum)

How does this line actually work in parallel and non-parallel ? My understanding is that in parallel, it takes the sum of each mini stream and adds it to the "total sum". Is that correct ? When stream is not parallel, then does it do zero + totalSum of single stream ? If yes, then a more accurate replacement for the previous line of code will be (sum, onePartialSum) -> (sum + onePartialSum) where sum is already initialized to zero ???

来源:https://stackoverflow.com/questions/60555563/understanding-java-stream-reduce-parallel-vs-series

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!