Java Reference
In-Depth Information
an optional type specification. If the type of the argument is not specified, then the type
is derived from the current context.
Lambda expressions are built on functional interfaces, which are simply Java inter-
faces containing a single abstract method. Simply put, the lambda expression itself is
an anonymous inner class that implements a functional interface, which can then be as-
signed to a variable and invoked. This recipe is merely a primer for lambda expres-
sions; to learn more about them, refer to
Chapter 6
.
2-2. Calling On an Existing Method from
a Lambda Expression
Problem
You are using a lambda expression to call on a single existing method that implements
a functional interface, and you'd like to shorten the length of the code required to per-
form this method call. Moreover, you want to be able to pass the method functionality
as an argument.
Solution
Utilize a method reference to call on a single existing method that implements a func-
tional interface. In the following example, a pool calculation class implements a func-
tional interface in order to obtain the calculated volume of a pool. The functional inter-
face
Volume
is as follows:
public interface Volume {
double calculateVolume();
}
The
PoolCalculator
class implements
Volume
, as it contains an implementa-
tion for the
calculateVolume()
method. Therefore, that method can be called on
via a method reference and assigned to a variable, which can then be passed as an argu-
ment as needed. The following code shows the
PoolCalculator
class.