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);
?
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())
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With