Java Reference
In-Depth Information
A Common Pattern Appears
max
and
min
are both forms of a more general pattern of coding. The easiest way to see this
the general pattern.
Example 3-14
performs the same role as
Example 3-13
:
it finds the
shortest track on an album, but using a
for
loop.
Example 3-14. Finding the shortest track with a for loop
List
<
Track
>
tracks
=
asList
(
new
new
Track
(
"Bakai"
,
524
),
new
new
Track
(
"Violets for Your Furs"
,
378
),
new
new
Track
(
"Time Was"
,
451
));
Track shortestTrack
=
tracks
.
get
(
0
);
for
for
(
Track track
:
tracks
) {
iif
(
track
.
getLength
() <
shortestTrack
.
getLength
()) {
shortestTrack
=
track
;
}
}
assertEquals
(
tracks
.
get
(
1
),
shortestTrack
);
The code starts by initializing our
shortestTrack
variable with the first element of the list.
Then it goes through the tracks. If there's a shorter track, it replaces the
shortestTrack
. At
the end, our
shortestTrack
variable contains its namesake. Doubtless you've written thou-
sands of
for
loops in your coding career, and many of them follow this pattern. The pseudo-
code in
Example 3-15
characterizes the general form.
Example 3-15. The reduce pattern
Object accumulator
=
initialValue
;
for
for
(
Object element
:
collection
) {
accumulator
=
combine
(
accumulator
,
element
);
}
An
accumulator
gets pushed through the body of the loop, with the final value of the
accu-
mulator
being the value that we were trying to compute. The
accumulator
starts with an
initialValue
and then gets folded together with each
element
of the list by calling
com-
bine
.
The things that differ between implementations of this pattern are the
initialValue
and the
combine
function. In the original example, we used the first element in the list as our
ini-