【发布时间】:2021-12-20 00:13:10
【问题描述】:
我很擅长 Java 流,所以也许这不是最小的解决方案,但这是我想出的使用流来获得我认为你想要的东西的方法:
我们是否将 DishDiet 作为 POJO 并将 DishDietTest 作为主类? 我正在根据需要获取数据,但如何循环它? 如何使用 Java 8 流迭代多级映射? 如何使用流完成基于分类的打印?
public class DishDiet {
private final String name;
private final boolean vegetarian;
private final int calories;
private final Type type;
private final CaloricLevel caloricLevel;
public DishDiet(String name, boolean vegetarian, int calories, Type type, CaloricLevel caloricLevel) {
this.name = name;
this.vegetarian = vegetarian;
this.calories = calories;
this.type = type;
this.caloricLevel = caloricLevel;
}
public String getName() {
return name;
}
public boolean isVegetarian() {
return vegetarian;
}
public int getCalories() {
return calories;
}
public Type getType() {
return type;
}
public CaloricLevel getCaloricLevel() {
return caloricLevel;
}
@Override
public String toString() {
return name;
}
public enum Type {
MEAT, FISH, OTHER
}
public enum CaloricLevel {
DIET, NORMAL, FAT
}
}
public class DishDietTest {
private static List<DishDiet> getAllDishDiet() {
return Arrays.asList(new DishDiet("pork", false, 800, DishDiet.Type.MEAT, DishDiet.CaloricLevel.FAT),
new DishDiet("beef", false, 700, DishDiet.Type.MEAT, DishDiet.CaloricLevel.FAT),
new DishDiet("chicken", false, 400, DishDiet.Type.MEAT, DishDiet.CaloricLevel.DIET),
new DishDiet("french fries", true, 530, DishDiet.Type.OTHER, DishDiet.CaloricLevel.NORMAL),
new DishDiet("rice", true, 350, DishDiet.Type.OTHER, DishDiet.CaloricLevel.DIET),
new DishDiet("season fruit", true, 120, DishDiet.Type.OTHER, DishDiet.CaloricLevel.DIET),
new DishDiet("pizza", true, 550, DishDiet.Type.OTHER, DishDiet.CaloricLevel.NORMAL),
new DishDiet("prawns", false, 300, DishDiet.Type.FISH, DishDiet.CaloricLevel.DIET),
new DishDiet("salmon", false, 450, DishDiet.Type.FISH, DishDiet.CaloricLevel.NORMAL));
}
public static void main(String[] args) {
Map<DishDiet.Type, Map<DishDiet.CaloricLevel, List<DishDiet>>> dishesByTypeCaloricLevel = getAllDishDiet()
.stream().collect(groupingBy(DishDiet::getType, groupingBy((dish -> {
if (dish.getCalories() <= 400)
return DishDiet.CaloricLevel.DIET;
else if (dish.getCalories() <= 700)
return DishDiet.CaloricLevel.NORMAL;
else
return DishDiet.CaloricLevel.FAT;
}
))));
System.out.println(dishesByTypeCaloricLevel);
}
}
【问题讨论】:
标签: java dictionary collections java-stream