Java: find the corresponding keys of two HashMaps

I have two HashMaps, for example HashMapA and HashMapB. What would be an effective way to find the keys that exist in both HashMaps? My current implementation is as follows:

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);

    }

}

This seems to work, but looks inefficient. There is something like

Integer keyInBothMaps = HashMapA.containsKeyOf(HashMapB);

?

+4
source share
2 answers

You can use Set.retainAll.

Here is an ugly example:

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);

Output

[b]
0
source

You are looking at the card keys, so start with keySet();

Then you can look at the interface Setand look at the methodretainAll

http://docs.oracle.com/javase/8/docs/api/java/util/Set.html#retainAll-java.util.Collection-

:

map1.keySet().retainAll(map2.keySet())

, :

new HashSet<>(map1.keySet()).retainAll(map2.keySet())
+1

Source: https://habr.com/ru/post/1539902/


All Articles