I proceed with java 8 learning.
I have found an interesting behavior:
let\'s see code sample:
// identity value and accumulator and combiner
Yes, you are breaking the contract of the combiner function. The identity, which is the first element of reduce, must satisfy combiner(identity, u) == u. Quoting the Javadoc of Stream.reduce:
The identity value must be an identity for the combiner function. This means that for all
u,combiner(identity, u)is equal tou.
However, your combiner function performs an addition and 1 is not the identity element for addition; 0 is.
Change the identity used to 0 and you will have no surprise: the result will be 72 for the two options.
For your own amusement, change your combiner function to perform a multiplication (keeping the identity to 1) and you will also notice the same result for both options.
Let's build an example where the identity is neither 0 or 1. Given your own domain class, consider:
System.out.println(Person.getPersons().stream()
.reduce("",
(acc, p) -> acc.length() > p.name.length() ? acc : p.name,
(n1, n2) -> n1.length() > n2.length() ? n1 : n2));
This will reduce the stream of Person to the longest person name.