Running the following stream example in Java8:
System.out.println(Stream
.of(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\")
.reduce(\"\", (s1,
For someone who just started with lambdas and streams, it took quite some time to get to the "AHA" moment, until I really understood what is going on here. I'll rephrase this a bit to make a bit easier (at least how I wish it was really answered) for a stream newbie like me.
It's all under the reduce documentation that states:
The identity value MUST be an identity for the accumulator function. This means that for all t, accumulator.apply(identity, t) is equal to t.
We can easily prove that the way code is, the associativity is broken:
static private void isAssociative() {
BinaryOperator operator = (s1, s2) -> s1 + "/" + s2;
String result = operator.apply("", "a");
System.out.println(result);
System.out.println(result.equals("a"));
}
An empty String concatenated with another String, should really produce the second String; which does not happen, thus accumulator (BinaryOperator) is NOT associative and thus the reduce method can not guarantee the same result in case of parallel invocation.