17.3.3 Terminal Operation reduce

You can define your own reductions for an IntStream by calling its reduce method as shown in lines 29–31 of Fig. 17.5. Each of the terminal operations in Section 17.3.2 is a specialized implementation of reduce. For example, line 31 shows how to sum an IntSteam’s values using reduce, rather than sum. The first argument (0) is a value that helps you begin the reduction operation and the second argument is an object that implements the IntBinaryOperator functional interface (package java.util.function). The lambda:

(x, y) -> x + y

implements the interface’s applyAsInt method, which receives two int values (representing the left and right operands of a binary operator) and performs a calculation with the values—in ...

Get Java™ How To Program (Early Objects), Tenth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.