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
# 1 楼答案
顺序流是确定性的,这意味着我们知道它执行的操作顺序:
并行流可以以任何顺序减少元素。您观察到的650例可能是通过以下操作实现的:
下次你可能会得到一个不同的顺序,从而得到不同的结果
# 2 楼答案
您的
reduce
操作取决于数组元素的相遇顺序parallelStream
忽略该顺序,并且每次调用并行执行时都会收到不同的值