//orderStockoutDetails中的每一项的getOrderDetailId对应的名称 Map<Long, String> skuNameMap = orderStockoutDetails.stream().collect(Collectors.toMap(OrderStockoutDetail::getOrderDetailId, OrderStockoutDetail::getSkuName, (i1, i2) -> i2)); //orderStockoutDetails中的每一项的getOrderDetailId对应的数量 Map<Long, Integer> skuAmount = orderStockoutDetails.stream().collect(Collectors.groupingBy(OrderStockoutDetail::getOrderDetailId, Collectors.summingInt(OrderStockoutDetail::getAmount))); //allItem中的每一项的getOrderDetailId对应的数量 Map<Long, Integer> skuAmount2 = allItem.stream().collect(Collectors.groupingBy(ShipItemDTO::getOrderDetailId, Collectors.summingInt(ShipItemDTO::getAmount)));//从condition.getSkuCodes()中遍历每一个skucode,如果skucode在skuAmount里存在则直接获取skuAmount里面对应skucode的amount值,否则就赋为0L,核心代码
countSkuAmountResponseDTO.setAmount(skuAmount.getOrDefault(it, 0L));
getOrDefault源代码
default V getOrDefault(Object key, V defaultValue) { V v; return (((v = get(key)) != null) || containsKey(key)) ? v : defaultValue; }意思就是去skuAmount中查找传来的key也就是本代码的it,判断是否在skuAmount里能找到这个key对应的内容,如果找不到就使用传过来的defaultValue作为值
Map<String, Long> skuAmount = skuAmountResponseDTOS .stream() .collect(Collectors.groupingBy(CountSkuAmountResponseDTO::getSkuCode, Collectors.summingLong(CountSkuAmountResponseDTO::getAmount))); return condition.getSkuCodes().stream().map(it -> { CountSkuAmountResponseDTO countSkuAmountResponseDTO = new CountSkuAmountResponseDTO(); countSkuAmountResponseDTO.setSkuCode(it); countSkuAmountResponseDTO.setAmount(skuAmount.getOrDefault(it, 0L)); return countSkuAmountResponseDTO; }).collect(Collectors.toList());couponInfoList.stream().filter(Objects::nonNull). ...当前对象不为空才会继续往下操作
Optional的使用
List<Integer> listAll = new ArrayList<>(); for (int i = 0; i < 100; i++) { Optional.ofNullable(1).ifPresent(listAll::add); } System.out.println(listAll.toString()); WuSongUser wuSongUser = new WuSongUser(); Optional.ofNullable("邬松").ifPresent(wuSongUser::setName); System.out.println(wuSongUser);