Java Reference
In-Depth Information
Calculating the Product of the Values with Method
reduce
Lines 39-41 of Fig. 17.5 use method
reduce
to calculate the product of the
IntSteam
's
values. In this case, the lambda multiplies its two arguments. Because we're producing a
product, we begin with the identity value
1
in this case. Evaluation of the reduction pro-
ceeds as follows:
• On the first call to
reduce
, lambda parameter
x
's value is the identity value (
1
)
and lambda parameter
y
's value is the
first
int
in the stream (
3
), producing the
value
3
(1 * 3).
• On the next call to
reduce
, lambda parameter
x
's value is the result of the first
calculation (
3
) and lambda parameter
y
's value is the
second
int
in the stream
(
10
), producing the sum
30
(3 * 10).
• On the next call to
reduce
, lambda parameter
x
's value is the result of the previ-
ous calculation (
30
) and lambda parameter
y
's value is the
third
int
in the stream
(
6
), producing the sum
180
(30 * 6).
This process continues producing a running product of the
IntSteam
's values until they've
all been used, at which point the final product is returned.
Values
Lines 45-48 of Fig. 17.5 create a stream pipeline that
locates
the even integers in an
Int-
Stream
,
sorts
them in ascending order and
displays
each value followed by a space.
Intermediate Operation
filter
You
filter
elements to produce a stream of intermediate results that match a condition—
known as a
predicate
.
IntStream
method
filter
(line 46) receives an object that imple-
ments the
IntPredicate
functional interface (package
java.util.function
). The lamb-
da in line 46:
value -> value %
2
==
0
implements the interface's
test
method, which receives an
int
and returns a
boolean
indi-
cating whether the
int
satisfies the predicate—in this case, the
IntPredicate
returns
true
if the value it receives is divisible by 2. Calls to
filter
and other intermediate streams are
lazy
—they aren't evaluated until a
terminal operation
(which is
eager
) is performed—and pro-
duce new streams of elements. In lines 45-48, this occurs when
forEach
is called (line 48).
Intermediate Operation
sorted
IntStream
method
sorted
orders the elements of the stream into
ascending
order. Like
filter
,
sorted
is a
lazy
operation; however, when the sorting is eventually performed, all
prior intermediate operations in the stream pipeline must be complete so that method
sorted
knows which elements to sort.
Processing the Stream Pipeline and Stateless vs. Stateful Intermediate Operations
When
forEach
is called, the stream pipeline is processed. Line 46 produces an intermedi-
ate
IntStream
containing only the even integers, then line 47 sorts them and line 48 dis-
plays each element.