是否有任何预定义的函数,我可以使用它来比较基于键的两个map并给出我的差异?现在,我迭代Map1并查找每个键,检查Map2中是否有元素,并进行模式匹配以查找差异。是否有更优雅的方法来做到这一点?
考虑转换为元组集合的映射之间的差异,
(m1.toSet diff m2.toSet).toMap
尝试:
val diff = (m1.keySet -- m2.keySet) ++ (m2.keySet -- m1.keySet)
diff
含有m1
中不含m2
的元素和m2
中不含m1
的元素。
这个解决方案看起来是正确的:
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
我认为--
操作符会做你正在寻找的:http://www.scala-lang.org/api/current/index.html#scala.collection.Map@—(xs:scala.collection.GenTraversableOnce[A]):Repr
虽然这可能只在假设Map2总是Map1的子集的情况下才有效…