I’m looking an efficient way to identify common keys of two HashMap
objects. One way would be to call hashKeys
on both and calculate the intersection. However this has n^2 complexity. The other way it to iterate through one, and for each key use get
to determine whether the key is in the second hash.
Here is the best way I can find to do this. It’s ugly because I’m simply returning None
from the flatMap to avoid accumulating a sequence.
def mapCommon[A,B](m1:HashMap[A,B], m2:HashMap[A,B], f:(A,B,B)=>Unit):Unit = {
m1.flatMap { case (k, v1) =>
m2.get(k).flatMap { v2 =>
f(k, v1, v2)
None
}
}
}
An alternate implementation which unfortunately accumulates a sequence just to throw it away is the following. It is more readable, in my opinion, but inefficient.
def mapCommon_alternate[A,B](m1:HashMap[A,B], m2:HashMap[A,B], f:(A,B,B)=>Unit):Unit = {
for{
(k,v1) <- m1
v2 <- m2.get(k)
} yield f(k,v1,v2)
}
it would be nice If I could ask the for expander to expand the inner most loop into a flatMap
rather than a map
, then I could do the following.
def mapCommon_alternate[A,B](m1:HashMap[A,B], m2:HashMap[A,B], f:(A,B,B)=>Unit):Unit = {
for{
(k,v1) <- m1
v2 <- m2.get(k)
_ = f(k,v1,v2)
} yield None // flatMap me rather than map
}