代码拉取完成,页面将自动刷新
package com.lun.c06;
import static java.util.stream.Collectors.*;
import java.util.Optional;
import static com.lun.c06.Dish.menu;
public class Reducing {
public static void main(String ... args) {
System.out.println("Total calories in menu: " + calculateTotalCalories());
System.out.println("Total calories in menu: " + calculateTotalCaloriesWithMethodReference());
System.out.println("Total calories in menu: " + calculateTotalCaloriesWithoutCollectors());
System.out.println("Total calories in menu: " + calculateTotalCaloriesUsingSum());
Optional<Dish> mostCalorieDish =
menu.stream().collect(reducing((d1, d2) -> d1.getCalories() > d2.getCalories() ? d1 : d2));
}
private static int calculateTotalCalories() {
return menu.stream().collect(reducing(0, Dish::getCalories, (Integer i, Integer j) -> i + j));
}
private static int calculateTotalCaloriesWithMethodReference() {
return menu.stream().collect(reducing(0, Dish::getCalories, Integer::sum));
}
private static int calculateTotalCaloriesWithoutCollectors() {
return menu.stream().map(Dish::getCalories).reduce(Integer::sum).get();
}
private static int calculateTotalCaloriesUsingSum() {
return menu.stream().mapToInt(Dish::getCalories).sum();
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。