jdk8按照多个字段对list分组

对一个list列表,按照一个字段进行分组,jdk8方式很方便实现:

List feeVOList = billFeeDao.listTotalFee(dto);
Map> feeGroup =  feeVOList.stream().filter(item->StringUtil.isNotBlank(item.getBizOperator()))
					.collect(Collectors.groupingBy(BillFeeVO::getBizOperator));

 

如果是按照多个字段进行分组,jdk8应该怎么实现呢?

首先生成一个Bean,重写equals和hashcode方法,把该Bean作为key即可。

 @Data
    @Builder
    private static class PickingGroupBean implements Comparable {

        // 库存占用明细 相关信息 -----
        // 库位id
        private Long storeLocationId;
        // 库位编码
        private String shelfOrder;
        // skuId
        private Long skuId;
        // 批次号
        private String batchNo;
        // 订单id
        private Long sendOrderMainId;
        // 单位id
        private Long unitId;
        // 库存占用明细 相关信息 -----

        @Override
        public int compareTo(PickingGroupBean o) {
            return shelfOrder.compareTo(o.shelfOrder);
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            PickingGroupBean that = (PickingGroupBean) o;
            if (!Objects.equals(storeLocationId,
                    that.storeLocationId)) {
                return false;
            }
            if (!Objects.equals(skuId, that.skuId)) {
                return false;
            }
            return Objects.equals(batchNo, that.batchNo);
        }

        @Override
        public int hashCode() {
            return Objects.hash(storeLocationId, skuId, batchNo);
        }
    }



//分组
private Map> groupStockAssignDetails(WaveGroup waveGroup,
                                                                                    List stockAssignDetailsList,
                                                                                    Map locationById) {
        // 1:分组
        Map> groupedSAD = new HashMap<>();
        for (StockAssignDetails stockAssignDetail : stockAssignDetailsList) {
            String shelfOrder = Optional.ofNullable(locationById.get(stockAssignDetail.getStoreLocationId()))
                    .map(LocationVO::getShelfOrder)
                    .orElse("");
            PickingGroupBean pickingGroupBean = PickingGroupBean.builder()
                    .shelfOrder(shelfOrder)
                    .storeLocationId(stockAssignDetail.getStoreLocationId())
                    .skuId(stockAssignDetail.getSkuId())
                    .batchNo(stockAssignDetail.getBatchNo())
                    .sendOrderMainId(stockAssignDetail.getSendOrderMainId())
                    .unitId(stockAssignDetail.getUnitId())
                    .build();
            groupedSAD.computeIfAbsent(pickingGroupBean, k -> new ArrayList<>())
                    .add(stockAssignDetail);
        }
        log.info("分组({}): {}", waveGroup.getId(), JSON.toJSONString(groupedSAD, true));
        return groupedSAD;
    }

 

你可能感兴趣的:(Java基础)