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
I'm not convinced I understand correctly, but I think the problem you're facing is how to call the functions in your List
? The JavaDoc for the Function interface states that it has a single non-abstract method, apply() that you call to use the Function, as follows:
public double getResult(){
double result = 0.0;
for(int i = 0; i < operations.size(); i++){
if(i == 0)
result = operations.get(i).apply(initialValue);
else
result += operations.get(i).apply(result);
}
return result;
}
As an aside, that method could be tidied up a bit to make it simpler:
public double getResult() {
double result = initialValue;
//Not sure if this if-statement is a requirement, but it is to replicate
//the functionality in the question
if (operations.isEmpty()) {
return 0.0;
}
for (Operation operation : operations) {
result = operation.apply(result);
}
return result;
}
And as others have said in the comments, you should use generics when passing around your List
objects (I guess you'll have to use something like List<Function<? extends Number, ? extends Number>
)
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<Function<Number, ? extends Number>> 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;
}