对象内部的 Hashmap 合并函数值

Hasmap merge function value inside an object

我正在尝试从销售清单中获取产品数量。所以我拥有的是:

public class sale {

    public String productId;
    .
    .//other sale variables
    .
    public int amountSold;
}

我目前的做法是基于这个整数答案: how to merge more than one hashmaps also sum the values of same key in java

所以,现在我正在遍历一个销售对象列表,对于每个销售对象,检查 hasmap 是否存在该产品的条目,如果没有,是否添加了多少产品在当前销售中被出售给它。

 HashMap<String,Integer> productSaleHash = new HashMap<>();
 saleList.forEach(sale -> {
     productSaleHash.merge(sale.getProductId(), sale.getAmountSold(), Integer::sum);
 });

这有效,但我必须将散列映射转换为数组列表,并将销售详细信息添加到每个条目中,因为我还想发送其他销售变量,例如 productName,而不仅仅是 id 和 salecount。因此,我试图找到一种更有效的方法来做到这一点。

这就是我想要做的,我创建了一个名为 productCount 的新 DTO 对象,而不是整数,我将对象存储在 hasmap 中。

public class productCount {

        public String productId;
        public String productName;
        public int amountSold;
    } 

HashMap<String,ProductCount> productSaleHash = new HashMap<>();
    saleList.forEach(sale -> {
        productSaleHash.merge(sale.getProductId(), sale.getAmountSold(), "add old amountSold with amount from sale" );
    });

让我们用构造函数和方法提升 ProductCount class:

public class ProductCount {
    public String productId;
    public String productName;
    public int amountSold;
    
    ProductCount(sale sale) {
         this.productId = sale.productId;
         this.amountSold = sale.amountSold;
         /* other initializations */
    }
    
    public ProductCount addAmountSoldFrom(ProductCount other) {
        this.amountSold += other.amountSold;
        return this;
    }
} 

现在 saleList 可以像这样遍历:

HashMap<String, ProductCount> productSaleHash = new HashMap<>();
saleList.forEach(sale ->
    productSaleHash.merge(sale.productId, new ProductCount(sale), ProductCount::addAmountSoldFrom);
);