how to merge more than one hashmaps also sum the values of same key in java

前端 未结 8 1550
清歌不尽
清歌不尽 2021-02-13 03:03

ı am trying to merge more than one hashmaps also sum the values of same key, ı want to explain my problem with toy example as follows

    HashMap

        
8条回答
  •  孤城傲影
    2021-02-13 03:22

    Something like this should work:

     for (Map.Entry entry : map.entrySet()) {
        String map1_key = entry.getKey();
        int map1_value = entry.getValue();
    
        //check:
        if(map2.get(map1_key)!=null){
        int map2_value = map2.get(map1_key);
        //merge:
        map3.put(map1_key,map1_value+map2_value);
        }else{
        map3.put(map1_key,map1_value);
        }
    }
    
    
      for (Map.Entry entry2 : map2.entrySet()) {
            String map2_key = entry2.getKey();
            int map2_value = entry2.getValue();
    
            //check:
            if(map1.get(map2_key)!=null){
            int map1_value = map1.get(map2_key);
            //merge:
            map3.put(map2_key,map1_value+map2_value);
            }else{
            map3.put(map2_key,map2_value);
            }
        }
    

提交回复
热议问题