Working with an ArrayList of Functions in Java-8

前端 未结 2 1378
慢半拍i
慢半拍i 2021-01-12 06:08

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

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-12 06:23

    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)

提交回复
热议问题