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

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

    This method should do it (in Java 5+)

    public static <K> Map<K, Integer> mergeAndAdd(Map<K, Integer>... maps) {
        Map<K, Integer> result = new HashMap<>();
        for (Map<K, Integer> map : maps) {
            for (Map.Entry<K, Integer> entry : map.entrySet()) {
                K key = entry.getKey();
                Integer current = result.get(key);
                result.put(key, current == null ? entry.getValue() : entry.getValue() + current);
            }
        }
        return result;
    }
    
    0 讨论(0)
  • 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<String, Integer> m = new HashMap<>();
            HashMap<String, Integer> m2 = new HashMap<>();
    
            m.put("apple", 2);
            m.put("pear", 3);
            m2.put("apple", 9);
            m2.put("banana", 6);
    
            final Map<String, Integer> result = (new MapMerger()).mergeSumOfMaps(m, m2);
            System.out.println(result);
        }
    
        public Map<String, Integer> mergeSumOfMaps(Map<String, Integer>... maps) {
            final Map<String, Integer> resultMap = new HashMap<>();
            for (final Map<String, Integer> 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)

    0 讨论(0)
提交回复
热议问题