Java8 List集合中的部份数据,按条件根据某个字段进行合并

2023-01-02 00:00:00 字段 合并 部份

前言:

在销售医药产品时,如果是中药销售,因为没有批号,所以将查询出来的数据全部按单位进行合并其库存后再销售

一、创建Product类

@Data
public class Product {
 
    /**id*/
    private String  productId;
    /**库存*/
    private double stockCount;
    /**采购数量*/
    private double purchaseCount;
     /**单位*/
    private String  unit;   
}

方法一:通过java的map来实现

 List<Product> list = new ArrayList<>();
    list.add(new Product(1, 10, 10));
    list.add(new Product(2, 11, 11));
    list.add(new Product(1, 12, 12));
 //如果是中药,合并库存
 
 Map<String, Product > map = new HashMap<>();
 for (Product productVO : list) {
     String id = productVO.getProductId();
     if (map.containsKey(id)) {
         Product s = map.get(id);
         String unit = s.getUnit();
         if (“KG".equalsIgnoreCase(unit) ||"千克".equalsIgnoreCase(unit) || "克".equalsIgnoreCase(unit) || "g".equalsIgnoreCase(unit)) {
             s.setStockCount(s.getStockCount().add(productVO.getStockCount()));
             s.setPurchaseCount(s.getPurchaseCount().add(productVO.getPurchaseCount()));
         }
         map.put(id, s);
     } else {
         map.put(id, productVO);
     }
 }

 List<Product > newList = new ArrayList<>();
 for (String temp : map.keySet()) {
     newList.add(map.get(temp));
 }
    System.out.println(newList );

方法二:通过Lamba表达式的groupingBy来实现

List<Product> list = new ArrayList<>();
list.add(new Product(1, 10, 10));
list.add(new Product(2, 11, 11));
list.add(new Product(1, 12, 12));

List<Product > newList = new ArrayList<>();
list.parallelStream().collect(Collectors.groupingBy(Product::getProductId, Collectors.toList()))
        .forEach((id, stu) -> {
            stu.stream().reduce((a, b) -> new Product (a.getProductId(), a.getStockCount() + b.getStockCount(), a.getpurchaseCount() + b.getpurchaseCount())).ifPresent(newList ::add);
        });

System.out.println(newList );

方法三:使用Lamba表达式的toMap来实现

List<Product> removalList = saleOrderDetails.stream()
                    .collect(Collectors.toMap(Product::getProductId, a -> a, (o1, o2) -> {
                        o1.setStockCount(o1.getStockCount().add(o2.getStockCount()));
                        o1.setSaleCount(o1.getSaleCount().add(o2.getSaleCount()));
                        o1.setSellAmount(o1.getSellAmount().add(o2.getSellAmount()));
                        return o1;
                    }))
                    .values()
                    .stream()
                    .filter(d -> {
                        return Objects.equals(d.getIsRxDrug(), 1) && Objects.equals(d.getIsNeedPrescription(), 1);
                    })
                    .collect(Collectors.toList());

QQ群:722865146
分布式商城下载:https://gitee.com/charlinchenlin/wysmall

    原文作者:lovoo
    原文地址: https://blog.csdn.net/lovoo/article/details/115318829
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。

相关文章