在Scala中,如何合并以下地图? [英] In Scala, how can I merge maps as below?
问题描述
我想知道如何在Scala中合并地图.
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"))
基本上,期望的地图是newMap +添加所有在prev和new之间具有不同键的值
Basically, expected map is newMap + add all values that had a different key between prev and new
谢谢
推荐答案
像这样使用标准库
m1 ++ m2.map { case (k,v) => k -> (v ++ m1.getOrElse(k,Set())) }
请考虑第一次出现++
,用于追加地图.通过将m1
中的集合与一个公共键合并,可以增强++
的右操作数的键值对,然后对于m1
和m2
中出现的任何键,运算符++
替换键值对m1
中的键值对在m2
中;保留m1
中没有出现键的m1
中的键值对.
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.
第二次出现的++
表示设置的联合方法.因此,仅在m2
中出现的那些键集保持不变(带有空集的集并集).
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).
这篇关于在Scala中,如何合并以下地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!