There are really two parts to your question. Why do you get 76 using parallel when you get 73 using serial. And that person, since multiplication and addition goes for Reduction.
The answer to the latter will help in answering the first part. Identity is a mathematical concept, I will try to stick to simple terms for those who are not mathematicians. Identity is a value that applies to itself, returns the same value.
The additive identity is 0. If we assumed that a is any number, then the identity property of the numbers means that a plus its identifier will return a . (basically a + 0 = a ). A multiplicative identity says that b times its identity, which is 1) always returns itself, b .
The java reduction method uses identification a little more mutably. Providing us the opportunity to say, we would like to perform addition and multiplication operations with an additional step, if we want. If you take your example: and change your personality to 0, you will get 72.
Integer summaryAge = Person.getPersons().stream() .reduce(0, (intermediateResult, p) -> intermediateResult + p.age, (ir1, ir2) -> ir1 + ir2); System.out.println(summaryAge);
It just sums the ages together and returns that value. Change it to 100, you will return 172. But when you execute the parallel, why does your result get 76, and in my example will return 472? Because when you use a stream, the results are considered a set, not individual elements. For JavaDocs in threads:
Threads facilitate parallel execution by updating the calculation as a conveyor of aggregate operations, rather than as mandatory operations for each individual element.
Why handling sets is important when using a standard thread (not: parallel or parallel thread), what you do in your example takes a sum and processes this single number. Therefore, you get 73 and change your identity to 100, I would get 172. But why is this so, using the parallel, you get 76? or in my example 472? Since java now splits the set into smaller (single) elements, adding its identifier (which you specified as 1), summing it, and then summing the result with the rest of the elements that performed the same operation.
If your intent is to add 1 to the result, it’s safer to follow Tagir’s suggestion and add 1 to the end after returning the stream.