【发布时间】:2020-08-22 04:45:15
【问题描述】:
class Dish {
public int getCalories() {
return calories;
}
public static final List<Dish> menu = Arrays.asList(
new Dish("pork", false, 800, Dish.Type.MEAT),
new Dish("beef", false, 700, Dish.Type.MEAT),
new Dish("chicken", false, 400, Dish.Type.MEAT),
new Dish("french fries", true, 530, Dish.Type.OTHER),
new Dish("rice", true, 350, Dish.Type.OTHER),
new Dish("season fruit", true, 120, Dish.Type.OTHER),
new Dish("pizza", true, 550, Dish.Type.OTHER),
new Dish("prawns", false, 400, Dish.Type.FISH),
new Dish("salmon", false, 450, Dish.Type.FISH)
);
}
当summingInt 需要ToIntFunction 时,以下Dish::getCalories 方法引用如何有效?我问是因为getcalories 的签名与applyAsInt 抽象方法ToIntFunction 的签名不匹配
int totalCalories = menu.stream().collect(summingInt(Dish::getCalories));
【问题讨论】:
-
它接受一个 Dish 并返回一个 int。等效的 lambda 为
d -> d.getCalories(); -
我明白这一点。但是
getCalories的签名与ToIntFunction中applyAsInt抽象方法的签名不匹配 -
@karanmirani 查看方法参考以了解在需要功能接口时它是如何工作的。
标签: java java-8 method-reference