Java:查找两个哈希映射的匹配键

Java:查找两个哈希映射的匹配键,java,hashmap,comparison,Java,Hashmap,Comparison,我有两个HashMap,比如HashMapA和HashMapB。查找两个哈希映射中存在的键的有效方法是什么?我当前的实现如下所示: Integer key; /* create iterator */ Iterator<Map.Entry<Integer, Foo>> it = HashMapA.entrySet().iterator; /* iterate through HashMapA using iterator*/ while (it.hasNext())

我有两个HashMap,比如HashMapA和HashMapB。查找两个哈希映射中存在的键的有效方法是什么?我当前的实现如下所示:

Integer key;

/* create iterator */
Iterator<Map.Entry<Integer, Foo>> it = HashMapA.entrySet().iterator;

/* iterate through HashMapA using iterator*/
while (it.hasNext()) {

    key = it.next().getKey();

    if (HashMapB.containsKey(key)) {

        /* matching key found */
        System.out.println("Got one: " + key);

    }

}

您可以使用
Set.retainal

下面是一个丑陋的例子:

Map<String, String> m0 = new HashMap<String, String>();
m0.put("a", "a");
m0.put("b", "b");
Map<String, String> m1 = new HashMap<String, String>();
m1.put("c", "c");
m1.put("b", "b");
Set<String> s = new HashSet<String>(m0.keySet());
s.retainAll(m1.keySet());
System.out.println(s);

您正在查看地图的键,因此请从
keySet()
开始

然后,您可以查看
Set
界面并查看方法
retainal

这将为您提供:

map1.keySet().retainAll(map2.keySet())
但是,这将修改贴图,因此您应该复制该集:

new HashSet<>(map1.keySet()).retainAll(map2.keySet())
newhashset(map1.keySet()).retainal(map2.keySet())

如果不清楚,请选中此处。您可以使用建议的副本计算两个地图的关键点集的交点。您可以获得两个关键点集,然后计算两个关键点集的交点。
map1.keySet().retainAll(map2.keySet())
new HashSet<>(map1.keySet()).retainAll(map2.keySet())