Java Reference
In-Depth Information
Figure 5.7. Using reduce to sum the numbers in a stream
Let's take an in-depth look into how the reduce operation happens to sum a stream of numbers.
First, 0 is used as the first parameter of the lambda (a), and 4 is consumed from the stream and
used as the second parameter (b). 0 + 4 produces 4, and it becomes the new accumulated value.
Then the lambda is called again with the accumulated value and the next element of the stream,
5, which produces the new accumulated value, 9. Moving forward, the lambda is called again
with the accumulated value and the next element, 3, which produces 12. Finally, the lambda is
called with 12 and the last element of the stream, 9, which produces the final value, 21.
You can make this code more concise by using a method reference. In Java 8 the Integer class
now comes with a static sum method to add two numbers, which is just what you want instead
of repeatedly writing out the same code as lambda:
int sum = numbers.stream().reduce(0, Integer::sum);
 
Search WWH ::




Custom Search