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
Using the standard library, like this,
Consider the first occurrence of
++
, for appending maps. The key value pairs of the right operand of++
are enhanced by merging sets fromm1
with a common key, then for any key occurring inm1
andm2
, the operator++
replaces the key value pair inm1
with the key value pair inm2
; key value pairs inm1
where the key does not occur inm2
are preserved.The second occurrence of
++
denotes the set union method. Thus, sets of those keys that occur only inm2
remain intact (set union with empty set).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 calleda
andb
)