Intersection and merge/join two maps in Scala

Viewed 3448

Let's say I have two maps that look something like this.

val m1 = Map(1 -> "One", 2 -> "Two", 3 -> "Three")
val m2 = Map(2 -> 2.0, 3 -> 3.0, 4 -> 4.0)

I want to get the intersection based on the keys and return a tuple that represents the merged values. The result would look like this.

Map(2 -> (Two,2.0), 3 -> (Three,3.0))

I suppose I can resort to something like

val merged = m1 collect {
  case (key, value) if m2.contains(key) => key -> (value, m2(key))
}

But is there no "more idiomatic" way to do that? My intuition was something similar to what I get with Set

val merged = m1.intersect(m2)
2 Answers
m1.keySet.intersect(m2.keySet).map(k => k->(m1(k),m2(k))).toMap
// res0: Map[Int,(String, Double)] = Map(2 -> (Two,2.0), 3 -> (Three,3.0))

Get the intersection of the keys and then map them into a new Map.

Convert m1 and m2 to List and concatenate. Then group by key and transform the result as required

val allList = m1.toList ++ m2.toList
val grouped = allList.groupBy(_._1)
val result = grouped.mapValues(lst => lst.map(_._2))
Related