Intersection and merge/join two maps in Scala

青春壹個敷衍的年華 提交于 2021-02-09 05:31:52

问题


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)

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/46552478/intersection-and-merge-join-two-maps-in-scala

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!