I proceed with java 8 learning.
I have found an interesting behavior:
let's see code sample:
// identity value and accumulator and combiner
Integer summaryAge = Person.getPersons().stream()
//.parallel() //will return surprising result
.reduce(1,
(intermediateResult, p) -> intermediateResult + p.age,
(ir1, ir2) -> ir1 + ir2);
System.out.println(summaryAge);
and model class:
public class Person {
String name;
Integer age;
///...
public static Collection<Person> getPersons() {
List<Person> persons = new ArrayList<>();
persons.add(new Person("Vasya", 12));
persons.add(new Person("Petya", 32));
persons.add(new Person("Serj", 10));
persons.add(new Person("Onotole", 18));
return persons;
}
}
12+32+10+18 = 72
. For sequential stream, this code always returns 73
which is 72 + 1
but for parallel, it always returns 76
which is 72 + 4*1
(4 is equal to stream elements count).
When I saw this result I thought that it is strange that parallel stream and sequential streams return different results.
Am I broke contract somewhere?
P.S.
for me, 73 is expected result but 76 is not.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…