构造一个 HashMap,在不覆盖键的情况下,将数组中的值相加到现有键上。

huangapple go评论69阅读模式
英文:

Construct a HashMap without overriding the key by summing the values to an existing key from an array

问题

我正试图从以下数组构建一个 HashMap

    product: [
     {
      id: 12345
      qty: 5
     },
     {
      id: 12345
      qty: 6
     },
     {
      id: 98765
      qty: 10
     }
    ]

**code:**

    HashMap<Long, Integer> productMap = new HashMap<>();
    int totalQty = 0;
    
    for (Product product : products) {
     Long id = product.getId();
     if (productMap.containsKey(id)) {
      productMap.put(id, totalQty + productMap.get(id).intValue());
     } else {
      productMap.put(id, totalQty);
     }
    }

从上面的方法中我正在检查地图中的键如果是则通过覆盖现有键将 qty 添加到 totalQty有没有更好的方法在求和值时不覆盖键呢
英文:

I'm trying to construct a HashMap from below array

product: [
 {
  id: 12345
  qty: 5
 },
 {
  id: 12345
  qty: 6
 },
 {
  id: 98765
  qty: 10
 }
]

code:

HashMap&lt;Long, Integer&gt; productMap = new HashMap&lt;&gt;();
int totalQty = 0;

for (Product product : products) {
 Long id = product.getId();
 if (productMap.containsKey(id)) {
  productMap.put(id, totalQty + productMap.get(id).intValue());
 } else {
  productMap.put(id, totalQty);
 }
}

from the above method I'm checking the key from the map, if yes add the qty to the totalQty by overriding the existing key, any best approach to not override the while summing the values ??

答案1

得分: 5

你可以这样做:

products.stream().collect(Collectors.toMap(Product::getId, Product::getQty, Integer::sum));
英文:

you can do like this:

products.stream().collect(toMap(Product::getId,Product::getQty,Intger::sum));

huangapple
  • 本文由 发表于 2020年4月8日 23:46:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/61104701.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定