Java Reference
In-Depth Information
System.out.println(sum);
ForkJoinPool.commonPool-worker-4 - Accumulator: partialSum = 0.0, person = (5, Laynie, FEMALE,
2012-12-13, 0.00), accumulated = 0.0
ForkJoinPool.commonPool-worker-2 - Accumulator: partialSum = 0.0, person = (6, Li, MALE,
2001-05-09, 2400.00), accumulated = 2400.0
ForkJoinPool.commonPool-worker-1 - Accumulator: partialSum = 0.0, person = (2, Jeff, MALE,
1970-07-15, 7100.00), accumulated = 7100.0
ForkJoinPool.commonPool-worker-2 - Combiner: a = 0.0, b = 2400.0, combined = 2400.0
ForkJoinPool.commonPool-worker-5 - Accumulator: partialSum = 0.0, person = (3, Donna, FEMALE,
1962-07-29, 8700.00), accumulated = 8700.0
main - Accumulator: partialSum = 0.0, person = (4, Chris, MALE, 1993-12-16, 1800.00),
accumulated = 1800.0
ForkJoinPool.commonPool-worker-3 - Accumulator: partialSum = 0.0, person = (1, Ken, MALE,
1970-05-04, 6000.00), accumulated = 6000.0
main - Combiner: a = 1800.0, b = 2400.0, combined = 4200.0
ForkJoinPool.commonPool-worker-5 - Combiner: a = 7100.0, b = 8700.0, combined = 15800.0
ForkJoinPool.commonPool-worker-5 - Combiner: a = 6000.0, b = 15800.0, combined = 21800.0
ForkJoinPool.commonPool-worker-5 - Combiner: a = 21800.0, b = 4200.0, combined = 26000.0
26000.0
The output shows that six threads (five fork/join worker threads and one main thread) performed the parallel
reduce operation. They all performed partial reduction using the accumulator to obtain partial results. Finally, the
partial results were combined using the combiner to get the result.
Sometimes you cannot specify a default value for a reduce operation. Suppose you want to get maximum integer
value from a stream of integers. If the stream is empty, you cannot default the maximum value to 0. In such a case, the
result is not defined. The third version of the reduce(BinaryOperator<T> accumulator) method is used to perform
such a reduction operation. The method returns an Optional<T> that wraps the result or the absence of a result. If
the stream contains only one element, that element is the result. If the stream contains more than one element, the
first two elements are passed to the accumulator, and subsequently, the partial result and the remaining elements are
passed to the accumulator. The following snippet of code computes the maximum of integers in a stream:
Optional<Integer> max = Stream.of(1, 2, 3, 4, 5)
.reduce(Integer::max);
if (max.isPresent()) {
System.out.println("max = " + max.get());
}
else {
System.out.println("max is not defined.");
}
max = 5
The following snippet of code tries to get the maximum of integers in an empty stream:
Optional<Integer> max = Stream.<Integer>empty()
.reduce(Integer::max);
if (max.isPresent()) {
System.out.println("max = " + max.get());
}
 
Search WWH ::




Custom Search