将方法引用作为参数传递

时间:2020-10-04 19:18:42

标签: java lambda method-reference

在这种情况下:

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作为总和,因为我的目的只是为了了解如何传递方法引用。

4 个答案:

答案 0 :(得分:2)

您的2个方法不带任何参数并返回一个对象,因此适合Supplier.get()方法。

请勿将Double变量用于sum,因为这将使自动装箱和自动拆箱的方式过多。

方法可以为static,因为它不使用任何字段或类的其他方法。

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

更好:

static double sumBy(Supplier<List<Double>> listGetter) {
    return listGetter.get().stream().mapToDouble(Double::doubleValue).sum();
}

答案 1 :(得分:1)

您似乎想要像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

答案 2 :(得分:0)

我认为您正在寻找Supplier<T>功能界面:

Double sumBy(Supplier<Collection<Double>> supplier) {
  Collection<Double> prices = supplier.get();
}

答案 3 :(得分:0)

使用Double sumBy(Supplier<List<Double>> doubles)

相关问题