有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在使用stream和parallelStream减少相同的数据数组时会产生不同的结果?

我在具有相同lambda表达式的同一数组上使用了reduce with stream和parallelStream,我期望得到相同的结果,但输出不同。然而,结果是不同的,我不知道为什么

守则:

    System.out.println("Reduce me...");
    Integer[] arrx = {1,2,3,4};
    //        Reducing the Array

    Arrays
            .stream(arrx)
            .reduce((s1, s2) -> (int)Math.pow(s1,2) + (int)Math.pow(s2,2))
            .ifPresent(System.out::println);

    Arrays.asList(arrx)
            .parallelStream()
            .reduce((s1, s2) -> (int)Math.pow(s1,2) + (int)Math.pow(s2,2))
            .ifPresent(System.out::println);

输出:

1172
650

共 (2) 个答案

  1. # 1 楼答案

    顺序流是确定性的,这意味着我们知道它执行的操作顺序:

    1^2 + 2^2 = 1 + 4 = 5
    5^5 + 3^2 = 25 + 9 = 34
    34^2 + 4^2 = 1156 + 16 = 1172
    

    并行流可以以任何顺序减少元素。您观察到的650例可能是通过以下操作实现的:

    1^2 + 2^2 = 5
    3^2 + 4^2 = 9 + 16 = 25
    5^2 + 25^2 = 25 + 625 = 650
    

    下次你可能会得到一个不同的顺序,从而得到不同的结果

  2. # 2 楼答案

    您的reduce操作取决于数组元素的相遇顺序

    parallelStream忽略该顺序,并且每次调用并行执行时都会收到不同的值