It's VERY hard to follow the Requirements for reduce() Arguments:
* The
identity must be defined such that for all elements in the stream
u, combiner.apply(identity,
u) is equal to
u.
* The
accumulator operator op must be associative and stateless such the (a op b) op c is equal to a op (b op c)
* The
combiner operator must also be associate and stateless and compatible with the identity, such that for all
u and t combiner.apply(
u, accumulator.apply(identity, t)) is equal to accumulator.apply(
u, t)
Can this be put in terms that are more easily understood? Maybe we can do some concrete examples here. I gather that identity just means the object (
string, integer, etc...) that we're starting off with.
Moving ahead to the example on the next page:
I'm not really understanding what's actually being done on the above list, regardless of whether I use stream() or parallelStream(). The result is not what I would expect. I.E., in the below example, I reduced the list to just two items to try to understand what's happening. I would expect to get 49, but I'm actually getting -51
If I use a parallelStream() it gives me -49, when I would expect 49...
//NOT AN ASSOCIATIVE ACCUMULATOR
System.out.println(Arrays.asList(50,1).parallelStream().reduce(0, (a,b) -> (a-b)));