是否有任何预定义的功能可以用来比较基于键的两个地图并给我区别?现在,我迭代Map1和foreach键,我检查Map2中是否有一个元素,我模式匹配以找到差异。有这么好的方法吗?
答案 0 :(得分:14)
考虑转换为元组集的映射之间的差异,
(m1.toSet diff m2.toSet).toMap
答案 1 :(得分:7)
尝试:
val diff = (m1.keySet -- m2.keySet) ++ (m2.keySet -- m1.keySet)
diff
包含m1
中但不在m2
中且在m2
而非m1
中的元素。
答案 2 :(得分:1)
我认为--
运算符会执行您要查找的内容:http://www.scala-lang.org/api/current/index.html#scala.collection.Map@--(xs:scala.collection.GenTraversableOnce[A]):Repr
虽然假设Map2始终是Map1的子集...
,这可能只会起作用答案 3 :(得分:1)
此解决方案看起来像正确的方法:
scala> val x = Map(1 -> "a", 2 -> "b", 3 -> "c")
x: scala.collection.immutable.Map[Int,String] = Map(1 -> a, 2 -> b, 3 -> c)
scala> val y = Map(1 -> "a", 2 -> "b", 4 -> "d")
y: scala.collection.immutable.Map[Int,String] = Map(1 -> a, 2 -> b, 4 -> d)
scala> val diff : Map[Int, String] = x -- y.keySet
diff: Map[Int,String] = Map(3 -> c)
在这里https://gist.github.com/frgomes/69068062e7849dfe9d5a53bd3543fb81