Java Lambda 分区方法再添加分组收集器
public class Menu {
/**
* 菜品名称
*/
private String name;
/**
* 菜品单价
*/
private Double price;
/**
* 菜品斤数
*/
private Double kilo;
/**
* 菜品类型:蔬菜、水果、肉类
*/
private String type;
public Menu() {
}
public Menu(String name, Double price, Double kilo, String type) {
super();
this.name = name;
this.price = price;
this.kilo = kilo;
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Double getKilo() {
return kilo;
}
public void setKilo(Double kilo) {
this.kilo = kilo;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
Menu pork = new Menu("猪肉", 9.9, 10.0, "肉类");
Menu beef = new Menu("牛肉", 38.8, 5.0, "肉类");
Menu chicken = new Menu("鸡肉", 6.5, 30.0, "肉类");
Menu tomato = new Menu("土豆", 3.5, 30.0, "蔬菜");
Menu potato = new Menu("西红柿", 7.5, 20.0, "蔬菜");
Menu apple = new Menu("苹果", 3.5, 20.0, "水果");
Menu orange = new Menu("橙子", 4.0, 20.0, "水果");
List<Menu> menuList = Arrays.asList(pork, beef, chicken, tomato, potato, apple, orange);
//获取便宜菜品分区,按菜品种类分组
Map<Boolean,Map<String, List<Menu>>> map = menuList.stream().collect(Collectors.partitioningBy(menu -> {
if (menu.getPrice() >= 10.0) {
return true;
} else {
return false;
}
}, Collectors.groupingBy(Menu::getType)));
Map<String, List<Menu>> m = map.get(false);
m.forEach((key, value) -> {
System.out.println(key);
value.forEach(me -> {
System.out.println("----->" + me.getName());
});
});
蔬菜
----->土豆
----->西红柿
肉类
----->猪肉
----->鸡肉
水果
----->苹果
----->橙子
//分别获取最贵、最便宜菜品中最大斤数菜品信息
Map<Boolean, Menu> map = menuList.stream().collect(Collectors.partitioningBy(menu -> {
if (menu.getPrice() >= 10.0) {
return true;
} else {
return false;
}
}, Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparing(Menu::getKilo)), Optional::get)));
map.forEach((key, value) -> {
System.out.println(key + " " + value.getName() + " " + value.getKilo());
});
false 鸡肉 30.0
true 牛肉 5.0
|