Java Reference
In-Depth Information
Using
this
in a Lambda That Appears in an Instance Method
As in an anonymous inner class, a lambda can use the outer class's
this
reference. In an
an anonymous inner class, you must use the syntax
OuterClassName
.this
—otherwise, the
this
reference would refer to
the object of the anonymous inner class
. In a lambda, you refer
to the object of the outer class, simply as
this
.
Parameter and Variable Names in a Lambda
The parameter names and variable names that you use in lambdas cannot be the same as as
any other local variables in the lambda's lexical scope; otherwise, a compilation error occurs.
Class
IntStream
provides various terminal operations for common stream reductions on
streams of
int
values. Terminal operations are
eager
—they immediately process the items
in the stream. Common reduction operations for
IntStream
s include:
•
count
(line 19) returns the number of elements in the stream.
•
min
(line 21) returns the smallest
int
in the stream.
•
max
(line 23) returns the largest
int
in the stream.
•
sum
(line 24) returns the sum of all the
int
s in the stream.
•
average
(line 26) returns an
OptionalDouble
(package
java.util
) containing
the average of the
int
s in the stream as a value of type
double
. For any stream,
it's possible that there are
no elements
in the stream. Returning
OptionalDouble
enables method
average
to return the average if the stream contains
at least one
element
. In this example, we know the stream has 10 elements, so we call class
OptionalDouble
's
getAsDouble
method to obtain the average. If there were no
elements
, the
OptionalDouble
would not contain the average and
getAsDouble
would throw a
NoSuchElementException
. To prevent this exception, you can in-
stead call method
orElse
, which returns the
OptionalDouble
's value if there is
one, or the value you pass to
orElse
, otherwise.
Class
IntStream
also provides method
summaryStatistics
that performs the
count
,
min
,
max
,
sum
and
average
operations
in one pass
of an
IntStream
's elements and returns the
results as an
IntSummaryStatistics
object (package
java.util
). This provides a signifi-
cant performance boost over reprocessing an
IntStream
repeatedly for each individual op-
eration. This object has methods for obtaining each result and a
toString
method that
summarizes all the results. For example, the statement:
System.out.println(IntStream.of(values).summaryStatistics());
produces:
IntSummaryStatistics{count=10, sum=55, min=1, average=5.500000,
max=10}
for the array values in Fig. 17.5.
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