Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Find matching keys of two HashMaps [duplicate]

I have two HashMaps, say HashMapA and HashMapB. What would be an efficient way of finding keys that exists in both HashMaps? My current implementation looks like this:

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 appears to work, but looks quiet inefficient. Is there something like

Integer keyInBothMaps = HashMapA.containsKeyOf(HashMapB);

?

like image 585
Simon Avatar asked May 09 '14 10:05

Simon


2 Answers

You are looking at the keys of the map so start with the keySet();

You can then look at the Set interface and see the method retainAll

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

This gives you:

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

However that will modify the map so you should copy the set:

new HashSet<>(map1.keySet()).retainAll(map2.keySet())
like image 166
Tim B Avatar answered Oct 20 '22 12:10

Tim B


You can use Set.retainAll.

Here's 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]
like image 23
Mena Avatar answered Oct 20 '22 12:10

Mena