1

I need help in making this java code of adding value to map efficient by making use of Java streams to perform this put to map action

  class Pair{
    String key;
    int value;
 }


void addtoMap(List<Pair> list){
    Map<String, Integer> hashMap= new HashMap();
    list.forEach(pair -> {
        if(hashMap.containsKey(pair.key))
        {
            int p= hashMap.get(pair.key);
            hashMap.put(pair.key,p+pair.value)
        }
        else 
            hashMap.put(pair.key,pair.value);
    });
}
 

hashMap.put("a",1); [["a",1]]
hashMap.put("b",2);  [["a",1],["b",2]]
hashMap.put("a',3);  [["a",4],["b",2]]
 
Sam
  • 165
  • 10

1 Answers1

3

You can use Collectors.toMap:

Map<String, Integer> hashMap =
    list.stream()
        .collect(Collectors.toMap(p -> p.key,
                                  p -> p.value,
                                  (v1,v2)->v1+v2));
Eran
  • 387,369
  • 54
  • 702
  • 768
  • 2
    Nice solution. The lambda `(v1,v2)->v1+v2` can also be replaced with `Integer::sum`. – Marc Jan 07 '21 at 06:49