如何通过键加入两个hashMap

时间:2014-08-10 07:18:27

标签: java map hashmap

我有两个HashMap。我需要通过他们的密钥加入两个hashMap。

Map<String, String> firstMap = new HashMap<String, String>();
Map<String, String> secondMap = new HashMap<String, String>();
firstMap= [{K1,V1},{K2,V2}]
secondMap= [{K2,V2},{K3,V3}]

我需要第三张地图

thirdMap= [{K2,V2}]

请帮助我。谢谢

5 个答案:

答案 0 :(得分:3)

此代码应该满足您的需求:

Map<String, String> thirdMap = new HashMap<String, String>();

for (String key : firstMap.keySet()) {
    if (secondMap.containsKey(key)) {
        thirdMap.put(key, firstMap.get(key));
    }
}

答案 1 :(得分:2)

firstMap.keySet().retainAll(secondMap.keySet());

这假设您可以更改firstMap。如果没有,请先复制一份:

Map<String, String> thirdMap = new HashMap<>(firstMap);

然后

thirdMap.keySet().retainAll(secondMap.keySet());

答案 2 :(得分:2)

Google Guava库有一个实用程序MapDifference,它可以区分两个地图。

MapDifference<String, String> diff = Maps.difference(map1, map2);

答案 3 :(得分:2)

执行以下操作:

Map<String, String> firstMap = new HashMap<>();
Map<String, String> secondMap = new HashMap<>();
Map<String, String> join = new HashMap<>();

for (Entry<String, String> entry : firstMap.entrySet())
    if (secondMap.containsKey(entry.getKey())) {
        String value = secondMap.get(entry.getKey());
        if (value.equals(entry.getValue())) {
            join.put(entry.getKey(), value);
        }
    }
}

答案 4 :(得分:2)

映射firstMap = new HashMap();     映射secondMap = new HashMap();

 // Add everything in firstMap 
    map2.putAll(Maps.difference(firstMap , secondMap ).entriesOnlyOnLeft());