1 Star 4 Fork 2

巨轮/LearnJava8

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
Summarizing.java 2.08 KB
一键复制 编辑 原始数据 按行查看 历史
巨轮 提交于 2020-08-13 22:19 +08:00 . First Commit
package com.lun.c06;
import java.util.*;
import java.util.function.*;
import static java.util.stream.Collectors.*;
import static com.lun.c06.Dish.menu;
public class Summarizing {
public static void main(String ... args) {
System.out.println("Nr. of dishes: " + howManyDishes());
System.out.println("The most caloric dish is: " + findMostCaloricDish());
System.out.println("The most caloric dish is: " + findMostCaloricDishUsingComparator());
System.out.println("Total calories in menu: " + calculateTotalCalories());
System.out.println("Average calories in menu: " + calculateAverageCalories());
System.out.println("Menu statistics: " + calculateMenuStatistics());
System.out.println("Short menu: " + getShortMenu());
System.out.println("Short menu comma separated: " + getShortMenuCommaSeparated());
}
private static long howManyDishes() {
return menu.stream().collect(counting());
}
private static Dish findMostCaloricDish() {
return menu.stream().collect(reducing((d1, d2) -> d1.getCalories() > d2.getCalories() ? d1 : d2)).get();
}
private static Dish findMostCaloricDishUsingComparator() {
Comparator<Dish> dishCaloriesComparator = Comparator.comparingInt(Dish::getCalories);
BinaryOperator<Dish> moreCaloricOf = BinaryOperator.maxBy(dishCaloriesComparator);
return menu.stream().collect(reducing(moreCaloricOf)).get();
}
private static int calculateTotalCalories() {
return menu.stream().collect(summingInt(Dish::getCalories));
}
private static Double calculateAverageCalories() {
return menu.stream().collect(averagingInt(Dish::getCalories));
}
private static IntSummaryStatistics calculateMenuStatistics() {
return menu.stream().collect(summarizingInt(Dish::getCalories));
}
private static String getShortMenu() {
return menu.stream().map(Dish::getName).collect(joining());
}
private static String getShortMenuCommaSeparated() {
return menu.stream().map(Dish::getName).collect(joining(", "));
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/jallenkwong/LearnJava8.git
git@gitee.com:jallenkwong/LearnJava8.git
jallenkwong
LearnJava8
LearnJava8
master

搜索帮助