首页 > 解决方案 > 如果键匹配,则为哈希图列表添加值

问题描述

我有一个哈希图列表。所有值都是整数。我想根据键匹配添加所有值。

假设我有一张像这样的地图:

Map<String, Integer> map1 = new HashMapMap<String, Integer>();
map1.put("RE", 14); 
map1.put("SE", 15); 
map1.put("DE", 13);

Map<String, Integer> map2 = new HashMapMap<String, Integer>(); 
map2.put("RE", 11); 
map2.put("SE", 10); 
map2.put("DE", 11);

Map<String, Integer> map3 = new HashMapMap<String, Integer>(); 
map3.put("RE", 1); 
map3.put("SE", 2); 


Map<String, Integer> map4 = new HashMapMap<String, Integer>(); 
map4.put("RE", 6); 
map4.put("SE", 7); 
map4.put("DE", 8);

现在我需要一张地图作为输出

Map<String, Integer> output= new HashMapMap<String, Integer>(); 
output.put("RE", 32); 
output.put("SE", 24); 
output.put("DE", 32);

标签: java

解决方案


如果您有一个哈希映射列表,那么您需要遍历每个哈希映射并将值添加/更新到您的输出哈希映射。像这样:

public static void main(String[] args) {
    HashMap<String, Integer> map1 = new HashMap<>();
    HashMap<String, Integer> output = new HashMap<>();
    for (Map.Entry<String, Integer> mapItem : map1.entrySet()) {
        if (!output.containsKey(mapItem.getKey())) {
            output.put(mapItem.getKey(), mapItem.getValue());
        } else {
            output.put(mapItem.getKey(), output.get(mapItem.getKey()) + mapItem.getValue());
        }
    }
}

推荐阅读