Intersection and merging / merging of two maps in Scala
Say I have two cards 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 a key-based intersection and return a tuple representing the combined values. The result will look as follows.
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 a “more idiomatic” way to do this? My intuition was something like what I get withSet
val merged = m1.intersect(m2)