jdk1.8 stream例子

1.分组求和1

@Override
    public void validStock(List<GoodsStockDO> goodsStockDOS, GoodsStockQueryReqDTO queryReqDTO) {
        if (CollectionUtil.isEmpty(goodsStockDOS)) {
            return;
        }
        // 先根据网点和仓库分组
        final Map<Long, List<GoodsStockDO>> collect = goodsStockDOS.stream().collect(Collectors.groupingBy(e ->
                e.getShopId() + '-' + e.getWareId()
        ));
        // 根据每组内的list对库存件数和库存金重进行求和
        final List<GoodsStockDO> collect1 = collect.entrySet().stream().map(e ->
                e.getValue().get(0)
                        .setStockNum(e.getValue().stream().mapToInt(GoodsStockDO::getStockNum).sum())
                        .setGoldWeight(e.getValue().stream().map(GoodsStockDO::getGoldWeight).reduce(INIT_BIG_DECIMAL, BigDecimal::add))
        ).collect(Collectors.toList());
    }

2.改进:分组求和2

    @Override
    public void validStock(List<GoodsStockDO> goodsStockDOS, GoodsStockQueryReqDTO queryReqDTO) {
        if (CollectionUtil.isEmpty(goodsStockDOS)) {
            return;
        }
        final Map<Long, GoodsStockDO> skuAndStockDOS = goodsStockDOS.stream().collect(
                Collectors.toMap(GoodsStockDO::getSkuId, Function.identity(), (prev, cur) -> {
                    final GoodsStockDO goodsStockDO = new GoodsStockDO();
                    goodsStockDO.setStockNum(prev.getStockNum() + cur.getStockNum());
                    goodsStockDO.setGoldWeight(prev.getGoldWeight().add(cur.getGoldWeight()));
                    return goodsStockDO;
                }));
        final List<GoodsStockDO> goodsStockListByDTO = this.goodsStockMapper.getGoodsStockListByDTO(queryReqDTO);
        goodsStockListByDTO.forEach(e -> {
            final GoodsStockDO goodsStockDO = skuAndStockDOS.get(e.getSkuId());
            AssertUtil.isTrue(ObjectUtil.isNull(goodsStockDO), String.format("款式[%s]在库存中不存在!", e.getSkuNo()));
        });
    }

3.多条件分组后value转set集合

// 生成委外订单的key与明细值
        final Map<String, Set<String>> groupAndSkuResp = skuListBySkuNos.stream().collect(Collectors.groupingBy(e ->
                        e.getSupplierId() + "," + e.getBigClassId() + "," + e.getTextureId()
                , Collectors.mapping(SkuRespVO::getSkuNo, Collectors.toSet())));

4. list集合中对象嵌套子集,对子集进行过滤分组

// 生成委外订单的key与明细值
        final Map<String, List<OutsourcingOrderDetailRespVO>> groupHeadAndDetails = demandOrderVOList.stream()
                .flatMap(demandOrder -> demandOrder.getDetailList().stream().map(detail ->
                        this.buildOutOrderDetail(demandOrder, detail)))
                .filter(e -> e.getOutsourcingNum() > 0)
                .collect(Collectors.groupingBy(e ->
                        e.getSupplierId() + "," + e.getBigClassId() + "," + e.getTextureId()));
                        
 // private OutsourcingOrderDetailRespVO buildOutOrderDetail

你可能感兴趣的:(java,list)