Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intersection and merge/join two maps in Scala

Tags:

scala

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)
like image 750
andyczerwonka Avatar asked Jan 04 '23 09:01

andyczerwonka


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

like image 162
jwvh Avatar answered Jan 12 '23 04:01

jwvh