我是 Java 8 的新手,流式收集器试图了解两者之间的基本区别是什么?
因为这两个代码都产生了相同的结果。一个使用return groupingBy(classifier, toList());并返回 groupingBy(classifier, HashMap::new,downstream);
这是代码
public class Grouping {
enum CaloricLevel { DIET, NORMAL, FAT };
public static void main(String[] args) {
System.out.println("Dishes grouped by type: " + groupDishesByType());
System.out.println("Dish names grouped by type: " + groupDishNamesByType());
}
private static Map<Type, List<Dish>> groupDishesByType() {
return Dish.menu.stream().collect(groupingBy(Dish::getType));
}
private static Map<Type, List<String>> groupDishNamesByType() {
return Dish.menu.stream().collect(groupingBy(Dish::getType, mapping(Dish::getName, toList())));
}
}
输出:
Dishes grouped by type: {MEAT=[pork, beef, chicken], OTHER=[french fries, rice, season fruit, pizza], FISH=[prawns, salmon]}
Dish names grouped by type: {MEAT=[pork, beef, chicken], OTHER=[french fries, rice, season fruit, pizza], FISH=[prawns, salmon]}
菜.java
public class Dish {
private final String name;
private final boolean vegetarian;
private final int calories;
private final Type type;
public Dish(String name, boolean vegetarian, int calories, Type type) {
this.name = name;
this.vegetarian = vegetarian;
this.calories = calories;
this.type = type;
}
public String getName() {
return name;
}
public boolean isVegetarian() {
return vegetarian;
}
public int getCalories() {
return calories;
}
public Type getType() {
return type;
}
public enum Type {
MEAT, FISH, OTHER
}
@Override
public String toString() {
return name;
}
}
qq_遁去的一_1
阿晨1998
炎炎设计
相关分类