Problem Description: I want to be able to use an ArrayList of Functions passed in from another class (where the Functions have been defined in that other c
The method
of a java.util.function.Function object is apply
. You need to call it like this:
operations.get(i).apply(initialValue)
However you use raw Function
and therefore the result could be Object
and you'd need to convert it to the appropriate type. Also you can't use the +
(or the +=
) operator with it. I'd suggest restricting the parameter types with Number
:
List> operations = Arrays.asList(
num -> num.intValue() + 1,
num -> num.intValue() - 1,
num -> num.doubleValue() * 3.14
); // just an example list here
public double getResult() {
double result = 0.0;
for (int i = 0; i < operations.size(); i++) {
if (i == 0) {
result = operations.get(i).apply(initialValue).doubleValue();
} else {
result += operations.get(i).apply(result).doubleValue();
}
}
return result;
}