Java Reference
In-Depth Information
assertEquals
(
6
,
count
);
The lambda expression returns the new
acc
value, which is the previous
acc
added to the
current element. The type of the reducer is a
BinaryOperator
, which we encountered in
NOTE
commended instead of the approach shown in this example in real code.
In fact, we could expand all the function applications that
reduce
to produce the code in
Example 3-17. Expanding the application of reduce
BinaryOperator
<
Integer
>
accumulator
= (
acc
,
element
) ->
acc
+
element
;
int
int
count
=
accumulator
.
apply
(
accumulator
.
apply
(
accumulator
.
apply
(
0
,
1
),
2
),
3
);
Table 3-1. Evaluating a sum reduce
element acc
Result
N/A
N/A 0
1
0
1
2
1
3
3
3
6
Let's look at the equivalent imperative Java code, written in
Example 3-18
,
so we can see
how the functional and imperative versions match up.