java使用stream()中的reducing实现将名字相同的累加(合并)点餐数量的,早餐,午餐,晚餐
Map<String, PersonFamilyFoodOrderDTO> mergedOrders = personFamilyFoodOrderDTOList.stream()
.collect(Collectors.groupingBy(PersonFamilyFoodOrderDTO::getUserName, Collectors.reducing(SysFoodOrderController::mergeOrder)))
.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().orElse(null)));
List<PersonFamilyFoodOrderDTO> collect = mergedOrders.values().stream()
.collect(Collectors.toList());
List<Optional<PersonFamilyFoodOrderDTO>> collect1 = personFamilyFoodOrderDTOList.stream()
.collect(Collectors.groupingBy(PersonFamilyFoodOrderDTO::getUserName,
Collectors.reducing(SysFoodOrderController::mergeOrder)))
.values().stream().collect(Collectors.toList());
private static PersonFamilyFoodOrderDTO mergeOrder(PersonFamilyFoodOrderDTO o1, PersonFamilyFoodOrderDTO o2) {
return new PersonFamilyFoodOrderDTO(o1.getUserName(),
o1.getBreakfast() + o2.getBreakfast(),
o1.getLunch() + o2.getLunch(),
o1.getDinner() + o2.getDinner(),
o1.getFamilyBreakfast() + o2.getFamilyBreakfast(),
o1.getFamilyLunch() + o2.getFamilyLunch(),
o1.getFamilyDinner() + o2.getFamilyDinner()
);
}
通过分组foodMenuDate,foodMenuType来统计OrderNumber总数
Map<String, Integer> sums = sysFoodOrderList.stream()
.collect(Collectors.groupingBy(p -> p.getFoodMenuDate() + "-" + p.getFoodMenuType()
,Collectors.summingInt(SysFoodOrder::getOrderNumber)));