Reputation: 532
While I was studying for my exams I encountered this question. Searched on google but couldn't find an answer.
When we concatenate two maps using either the ++ operator or the Map.++() method duplicate keys will get removed. But what will happen if there are duplicate keys but different values for the keys in two maps, which one will be removed?
ex:
Map1 contains key1->"hello"
Map2 contains key1->"world"
Here keys have the same name but the values are different so what will be the key-value pairs in the output map when Map1 and Map2 are concatenated?
Upvotes: 1
Views: 1202
Reputation: 4554
If you'd like to be explicit in overriding/merging logic you can do something like:
val map1 = Map("key1" -> "hello")
val map2 = Map("key1" -> "world")
val jointKeys = map1.keySet.intersect(map2.keySet)
val overlap = jointKeys.map(key => (key -> map2(key))).toMap // or use whatever custom override/concatenate logic instead of this lambda
val merged = overlap ++ map1.filterKeys(jointKeys) ++ map2.filterKeys(jointKeys)
Upvotes: 3