让我举两个例子。首先,身份被破坏:
int result = Stream.of(1, 2, 3, 4, 5, 6) .parallel() .reduce(10, (a, b) -> a + b);System.out.println(result); // 81 on my run
基本上,您已经违反了以下规则:
The identity value must be an identity for the accumulatorfunction. This means that for all u, accumulator(identity, u) is equal to u。
或更简单地说,让我们看看该规则是否适用于Stream中的一些随机数据:
Integer identity = 10; BinaryOperator<Integer> combiner = (x, y) -> x + y; boolean identityRespected = combiner.apply(identity, 1) == 1; System.out.println(identityRespected); // prints false
第二个例子:
private static int howMany(List<String> tokens) { return tokens.stream() .parallel() .reduce(0, // identity (i, s) -> { // accumulator return s.length() + i; }, (left, right) -> { // combiner return left + right + left; // notice the extra left here });}然后使用以下命令调用它:
List<String> left = Arrays.asList("aa", "bbb", "cccc", "ddddd", "eeeeee");List<String> right = Arrays.asList("aa", "bbb", "cccc", "ddddd", "eeeeee", "");System.out.println(howMany(left)); // 38 on my runSystem.out.println(howMany(right)); // 50 on my run基本上,您已经违反了此规则:
Additionally, the combiner function must be compatible with theaccumulator function或在代码中:
// this must hold!// combiner.apply(u, accumulator.apply(identity, t)) == accumulator.apply(u, t)Integer identity = 0;String t = "aa";Integer u = 3; // "bbb"BiFunction<Integer, String, Integer> accumulator = (Integer i, String s) -> i + s.length();BinaryOperator<Integer> combiner = (left, right) -> left + right + left;int first = accumulator.apply(identity, t); // 2int second = combiner.apply(u, first); // 3 + 2 + 3 = 8Integer shouldBe8 = accumulator.apply(u, t);System.out.println(shouldBe8 == second); // false



