【问题标题】:Hasmap merge function value inside an object对象内的Hashmap合并函数值
【发布时间】:2021-08-07 23:10:19
【问题描述】:

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

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

【问题讨论】:

  • 您想在 HashMap 中用名称替换 ID 吗?合并部分之后
  • 当您使用sale 对象(没有此类属性)时,productName 来自哪里?
  • @azro 不,我正在尝试计算产品销售量。
  • @ernest_k 我不确定你的意思?

标签: java hash hashmap


【解决方案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);
);

【讨论】:

  • 这行得通,谢谢。尽管我认为创建一个新对象而不是像这样更新对象中的变量违反了 OOP 的核心原则。我需要找到一种访问对象的方法。
  • @Oirampok 您还可以使用 lambda 表达式代替方法引用并修改在 merge 方法中创建的对象:(oldCount, newCount) -&gt; { newCount.amountSold += oldCount.amountSold; return newCount; }
猜你喜欢
  • 2017-02-06
  • 1970-01-01
  • 1970-01-01
  • 2020-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-04
相关资源
最近更新 更多