java使用stream()中的reducing实现将名字相同的累加(合并)点餐数量的,早餐,午餐,晚餐

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()
                );
    }

你可能感兴趣的:(java,开发语言)