Java Reference
In-Depth Information
}
Each element of numbers is combined iteratively with the addition operator to form a result.
You reduce the list of numbers into one number by repeatedly using addition. There are two
parameters in this code:
The initial value of the sum variable, in this case 0
The operation to combine all the elements of the list, in this case +
Wouldn't it be great if you could also multiply all the numbers without having to repeatedly copy
and paste this code? This is where the reduce operation, which abstracts over this pattern of
repeated application, can help. You can sum all the elements of a stream as follows:
int sum = numbers.stream().reduce(0, (a, b) -> a + b);
reduce takes two arguments:
An initial value, here 0 .
A BinaryOperator<T> to combine two elements and produce a new value; here you use the lambda
(a,b) -> a+ b .
You could just as easily multiply all the elements by passing a different lambda, (a, b) -> a * b, to
the reduce operation:
int product = numbers.stream().reduce(1, (a, b) -> a * b);
Figure 5.7 illustrates how the reduce operation works on a stream: the lambda combines each
element repeatedly until the stream is reduced to a single value.
 
Search WWH ::




Custom Search