将方法引用作为参数传递

在这种情况下:

public class Order {
    List<Double> prices = List.of(1.00, 10.00, 100.00);
    List<Double> pricesWithTax = List.of(1.22, 12.20, 120.00);

    Double sumBy(/* method reference */) {
        Double sum = 0.0;
        for (Double price : /* method reference */) {
            sum += price;
        }
        return sum;
    }

    public List<Double> getPrices() { return prices; }
    public List<Double> getPricesWithTax() { return pricesWithTax; }
}

我如何sumBy以这样的方式声明方法:

Order order = new Order();
var sum = order.sumBy(order::getPrices);
var sumWithTaxes = order.sumBy(order::getPricesWithTax);

我不使用Java 8 API作为总和,因为我的目标只是了解如何传递方法引用。

艾略特新鲜

你似乎想要一个Supplier

Double sumBy(Supplier<List<Double>> f) {
    Double sum = 0.0;
    for (Double price : f.get()) {
        sum += price;
    }
    return sum;
}

您的List.of语法给了我错误。所以我做了

List<Double> prices = Arrays.asList(1.00, 10.00, 100.00);
List<Double> pricesWithTax = Arrays.asList(1.22, 12.20, 120.00);

然后我测试像

public static void main(String[] args) throws IOException {
    Order order = new Order();
    double sum = order.sumBy(order::getPrices);
    double sumWithTaxes = order.sumBy(order::getPricesWithTax);
    System.out.printf("%.2f %.2f%n", sum, sumWithTaxes);
}

产出

111.00 133.42

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章