In Scala, how can I merge maps as below?

我只是一个虾纸丫 提交于 2019-12-25 03:59:26

问题


I would like to know how I can merge maps in Scala.

val prevMap = Map(1-> Set("a"), 2-> Set("b"))
val newMap = Map(2-> Set("a","b"),1-> Set("c"))
val expected = Map(1->Set("a","c"), 2-> Set("a","b"))

Basically, expected map is newMap + add all values that had a different key between prev and new

Thanks


回答1:


Using the standard library, like this,

m1 ++ m2.map { case (k,v) => k -> (v ++ m1.getOrElse(k,Set())) }

Consider the first occurrence of ++, for appending maps. The key value pairs of the right operand of ++ are enhanced by merging sets from m1 with a common key, then for any key occurring in m1 and m2, the operator ++ replaces the key value pair in m1 with the key value pair in m2; key value pairs in m1 where the key does not occur in m2 are preserved.

The second occurrence of ++ denotes the set union method. Thus, sets of those keys that occur only in m2 remain intact (set union with empty set).




回答2:


I wouldn't know that there is a built-in function for that (after all, it depends on the specific Set value type). Here is the most compact I was able to come up with (assume maps are called a and b)

(a.keySet | b.keySet) map { k => k -> (a.getOrElse(k, Set.empty) | b.getOrElse(k, Set.empty)) } toMap


来源:https://stackoverflow.com/questions/26153967/in-scala-how-can-i-merge-maps-as-below

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