Java Reference
In-Depth Information
Double[] argList2 = new Double[2];
argList2[0] = x;
argList2[1] = y;
PassingLambdaFunctions p1 = new
PassingLambdaFunctions();
// Pass the lambda expressions to the calculate()
method, along with the
// argument lists.
System.out.println("The volume is: "
+ p1.calculate(volumeCalc, argList));
System.out.println("The area is: "
+ p1.calculate(areaCalc, argList2));
}
}
Result:
The volume is: 1920.0
The area is: 480.0
How It Works
Lambda expressions can be assigned to variables of the same type as the functional in-
terface being implemented. Such expressions can contain a single-line expression or a
multi-statement body. Since the lambda expression can accept arguments, there are use
cases for assigning such expressions to variables and then passing those variables into
other objects to modify functionality. This pattern is useful for creating solutions that
may contain more than one implementation. The solution to this recipe demonstrates
this concept.
In the solution, a class named PassingLambdaFunctions contains a single
method identified as calculate() . The calculate() method is to be used for
performing calculations on Double values that are passed into it as arguments.
However, the calculate() method contains no calculation functionality at all.
Rather, the calculation functionality is passed into it as an argument of type Func-
tion<List<Double>,Double> via a lambda expression. This type is actually
Search WWH ::




Custom Search