Java Reference
In-Depth Information
tialValue
, but it doesn't have to be. In order to find the shortest value, our
combine
re-
turned the shorter track of out of the current
element
and the
accumulator
.
We'll now take a look at how this general pattern can be codified by an operation in the
Streams API itself.
reduce
Use the
reduce
operation when you've got a collection of values and you want to generate a
single result. In earlier examples, we used the
count
,
min
, and
max
methods, which are all in
the standard library because they are common use cases. All of these are forms of reduction.
Let's demonstrate the
reduce
operation by adding up streams of numbers. The overall pat-
tern is demonstrated in
Figure 3-8
. We start with a count of 0—the count of an empty
Stream
—and fold together each element with an accumulator, adding the element to the ac-
cumulator at every step. When we reach the final
Stream
element, our accumulator has the
sum of all the elements.
Figure 3-8. Implementing addition using the reduce operation
Example 3-16
shows what is going on in code. The lambda expression, known as a
reducer
,
performs the summing and takes two arguments.
acc
is the accumulator and holds the cur-
rent sum. It is also passed in the current element in the
Stream
.
Example 3-16. Implementing sum using reduce
int
int
count
=
Stream
.
of
(
1
,
2
,
3
)
.
reduce
(
0
, (
acc
,
element
) ->
acc
+
element
);