Working with an ArrayList of Functions in Java-8

前端 未结 2 1393
慢半拍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:41

    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;
    }
    

提交回复
热议问题