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

前端 未结 8 1547
清歌不尽
清歌不尽 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:43

    Here's my quick and dirty implementation:

    import java.util.HashMap;
    import java.util.Map;
    
    public class MapMerger {
    
        public static void main(String[] args) {
            HashMap m = new HashMap<>();
            HashMap m2 = new HashMap<>();
    
            m.put("apple", 2);
            m.put("pear", 3);
            m2.put("apple", 9);
            m2.put("banana", 6);
    
            final Map result = (new MapMerger()).mergeSumOfMaps(m, m2);
            System.out.println(result);
        }
    
        public Map mergeSumOfMaps(Map... maps) {
            final Map resultMap = new HashMap<>();
            for (final Map map : maps) {
                for (final String key : map.keySet()) {
                    final int value;
                    if (resultMap.containsKey(key)) {
                        final int existingValue = resultMap.get(key);
                        value = map.get(key) + existingValue;
                    }
                    else {
                        value = map.get(key);
                    }
                    resultMap.put(key, value);
                }
            }
            return resultMap;
        }
    }
    

    Output:

    {banana=6, apple=11, pear=3}
    

    There are some things you should do (like null checking), and I'm not sure if it's the fastest. Also, this is specific to integers. I attempted to make one using generics of the Number class, but you'd need this method for each type (byte, int, short, longer, etc)

提交回复
热议问题