In Scala, how can I merge maps as below?

2019-09-17 21:41发布

问题:

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