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

Viewed 88

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

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 Answers

you can do like this:

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