Java Reference
In-Depth Information
You can solve this problem by mapping each element of a stream into the number 1 and then
summing them using reduce! This is equivalent to counting in order the number of elements in
the stream.
int count = menu.stream()
.map(d -> 1)
.reduce(0, (a, b) -> a + b);
A chain of map and reduce is commonly known as the map-reduce pattern, made famous by
Google's use of it for web searching because it can be easily parallelized. Note that in chapter 4
you saw the built-in method count to count the number of elements in the stream:
long count = menu.stream().count();
Benefit of the reduce method and parallelism
The benefit of using reduce compared to the step-by-step iteration summation that you wrote
earlier is that the iteration is abstracted using internal iteration, which enables the internal
implementation to choose to perform the reduce operation in parallel. The iterative summation
example involves shared updates to a sum variable, which doesn't parallelize gracefully. If you
add in the needed synchronization, you'll likely discover that thread contention robs you of all
the performance that parallelism was supposed to give you! Parallelizing this computation
requires a different approach: partition the input, sum the partitions, and combine the sums.
But now the code is starting to look really different. You'll see what this looks like in chapter 7
using the fork/join framework. But for now it's important to realize that the mutable
accumulator pattern is a dead end for parallelization. You need a new pattern, and this is what
reduce provides you. You'll also see in chapter 7 that to sum all the elements in parallel using
streams, there's almost no modification to your code: stream() becomes parallelStream():
int sum = numbers.parallelStream().reduce(0, Integer::sum);
But there's a price to pay to execute this code in parallel, as we explain later: the lambda passed
to reduce can't change state (for example, instance variables), and the operation needs to be
associative so it can be executed in any order.
Search WWH ::




Custom Search