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)
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
.
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