java 通过map根据list某个字段进行合并

 

 

List<WarehouseStockItemBean> warehouseStockItemBeanLists = new ArrayList<>();
List<WarehouseStockItemBean> warehouseStockItemBeans = new ArrayList<>();
Map<Long, WarehouseStockItemBean> map = new HashMap<>();
        for (WarehouseStockItemBean warehouseStockItemBean : warehouseStockItemBeanLists) {
            Long id = warehouseStockItemBean.getCommodityId();//获取commodity_id根据commodity_id进行合并
            if (map.containsKey(id)) {//查看map里是否包含这个commodity_id
                WarehouseStockItemBean warehouseStockItem = map.get(id);拿到map里包含符合条件的数据
                warehouseStockItem.setQuantity(warehouseStockItem.getQuantity().add(warehouseStockItemBean.getQuantity()));//将quantity进行相加
                map.put(id, warehouseStockItem);
            } else {
                map.put(id, warehouseStockItemBean);
            }
        }
        for (Long temp : map.keySet()) {
            warehouseStockItemBeans.add(map.get(temp));
        }

 

posted @ 2021-01-19 11:24  卟萌  阅读(1507)  评论(0编辑  收藏  举报