有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

对象内的java Hasmap合并函数值

我正试图从销售清单中获得产品的数量。所以我得到的是:

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);
 });

这是可行的,但我必须将hashmap转换为arraylist,并在每个条目中添加销售详细信息,因为我还想发送其他销售变量,例如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" );
    });

共 (1) 个答案

  1. # 1 楼答案

    让我们用构造函数和方法增强ProductCount类:

    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);
    );