"Tw...">

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)
+4
source share
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 mapthem into a new one map.

+5
source

Convert to m1and m2to List. Then group the key and transform the result as needed

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

Source: https://habr.com/ru/post/1686837/