Java Reference
In-Depth Information
one of the standard functional interfaces contained within the
java.util.function
package (see Recipe 6-2), and the interface can be imple-
mented by lambda expressions and then invoked at a later time by calling its solo
ap-
ply()
method. Looking at the code in the
calculate()
method, the arguments
contained within the
Double[]
are first added to a list. Next, lambda expression's
apply()
method is invoked, passing the new list of values, and returning a result into
returnVal
. Finally,
returnVal
is returned to the method invoker.
returnVal=f1.apply(varList);
return returnVal;
To implement the calculation functionality within the solution, lambda expressions
are created in a separate class named
MainClass
. Each expression accepts a list of
arguments and then performs a calculation on the values in the list, returning a result.
For instance, the first lambda generated in the
MainClass
calculates volume by mul-
tiplying together all of the values contained in the argument list and returns the result.
This functionality is then assigned to a variable of type
Func-
tion<List<Double>,Double>
, and then it is passed into the
PassingLambdaFunctions.calculate()
method later on.
Any type of functionality can be implemented within a lambda expression and then
passed around to different objects for use. This is an excellent way to promote code re-
use and high maintainability.
6-9. Invoking Existing Methods by Name
Problem
You are developing a lambda expression that merely invokes a method that already ex-
ists in the object being passed to the lambda.
Solution
Use a method reference, rather than writing a lambda expression, to call an existing
method. In the following scenario, the
Player
object contains a static method named
compareByGoals()
, which takes two
Player
objects and compares the number
of goals each contains. It then returns an integer representing the outcome. For all in-