Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zip two HashMaps(or dictionaries)

What would be a functional way to zip two dictionaries in Scala?

map1 = new HashMap("A"->1,"B"->2)
map2 = new HashMap("B"->22,"D"->4) // B is the only common key

zipper(map1,map2) should give something similar to

 Seq( ("A",1,0), // no A in second map, so third value is zero
      ("B",2,22),
      ("D",0,4)) // no D in first map, so second value is zero 

If not functional, any other style is also appreciated

like image 544
RAbraham Avatar asked Apr 28 '13 00:04

RAbraham


1 Answers

def zipper(map1: Map[String, Int], map2: Map[String, Int]) = {
  for(key <- map1.keys ++ map2.keys)
    yield (key, map1.getOrElse(key, 0), map2.getOrElse(key, 0))
}


scala> val map1 = scala.collection.immutable.HashMap("A" -> 1, "B" -> 2)
map1: scala.collection.immutable.HashMap[String,Int] = Map(A -> 1, B -> 2)

scala> val map2 = scala.collection.immutable.HashMap("B" -> 22, "D" -> 4)
map2: scala.collection.immutable.HashMap[String,Int] = Map(B -> 22, D -> 4)

scala> :load Zipper.scala
Loading Zipper.scala...
zipper: (map1: Map[String,Int], map2: Map[String,Int])Iterable[(String, Int, Int)]

scala> zipper(map1, map2)
res1: Iterable[(String, Int, Int)] = Set((A,1,0), (B,2,22), (D,0,4))

Note using get is probably preferable to getOrElse in this case. None is used to specify that a value does not exist instead of using 0.

like image 190
Brian Avatar answered Nov 16 '22 03:11

Brian