Java Reference
In-Depth Information
Note that the second argument, which is the accumulator, takes an argument whose type may be different from
the type of the stream. This is used for the map operation as well as for the accumulating the partial results. The third
argument is used for combining the partial results when the reduce operation is performed in parallel, which I will
elaborate upon shortly. The following snippet of code prints the sum of the incomes of all people:
double sum = Person.persons()
.stream()
.reduce(0.0, (partialSum, person) -> partialSum + person.getIncome(), Double::sum);
System.out.println(sum);
26000.0
If you examine the code, the second argument to the reduce() method is sufficient to produce the desired result
in this case. So, what is the purpose of the third argument, Double::sum , which is the combiner? In fact, the combiner
was not used in the reduce() operation at all, even if you specified it. You can verify that the combiner was not used
using the following code, which prints a message from the combiner:
double sum = Person.persons()
.stream()
.reduce(0.0, (partialSum, person) -> partialSum + person.getIncome(),
(a, b) -> {
System.out.println("Combiner called: a = " + a + "b = " + b );
return a + b;
});
System.out.println(sum);
26000.0
The output proves that the combiner was not called. Why do you need to provide the combiner when it is not
used? It is used when the reduce operation is performed in parallel. In that case, each thread will accumulate the
partial results using the accumulator. At the end, the combiner is used to combine the partial results from all threads
to get the result. The following snippet of code shows how the sequential reduce operation works. The code prints a
message at several steps along with the current thread name that is performing the operation.
double sum = Person.persons()
.stream()
.reduce(0.0,
(Double partialSum, Person p) -> {
double accumulated = partialSum + p.getIncome();
System.out.println(Thread.currentThread().getName() +
" - Accumulator: partialSum = " +
partialSum + ", person = " + p +
", accumulated = " + accumulated);
return accumulated;
},
 
Search WWH ::




Custom Search