Java Reference
In-Depth Information
public class PassingLambdaFunctions {
/**
* Calculates a value based upon the calculation
function that is passed
* in.
* @param f1
* @param args
* @param x
* @param y
* @param z
* @return
*/
public Double calculate(Function<List<Double>,
Double> f1,
Double [] args){
Double returnVal;
List<Double> varList = new ArrayList();
int idx = 0;
while (idx < args.length){
varList.add(args[idx]);
idx++;
}
returnVal=f1.apply(varList);
return returnVal;
}
}
To make use of the calculate method, a lambda expression that implements
Func-
tion<List<Double>,Double>
must be passed as the first argument to the
cal-
culate()
method, along with an array of
Double
arguments that contains the value
to be used within the calculation. In the following class, a function for calculating
volume is generated using a lambda expression, and it is assigned to variable identified
as
volumeCalc
of type
Function<List<Double>,Double>
. Another lambda
expression is used to create a function for calculating area, and it is assigned to a vari-
able of the same type, identified as
areaCalc
. In separate calls, these variables are
then passed to the
PassingLambdaFunctions.calculate()
method, along
with an array of values, resulting in the calculated answer.