比较 Scala 中的两个 Map

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24827462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:25:14  来源:igfitidea点击:

Compare two Maps in Scala

scalascala-collections

提问by sparkr

Is there any pre-defined function that I can use to compare two Maps based on the key and give me the difference? Right now, I iterate Map1 and foreach key, I check if there is an element in Map2 and I pattern match to find the difference. Is there a much elegant way to do this?

是否有任何预定义的函数可用于根据键比较两个 Map 并给出差异?现在,我迭代 Map1 和 foreach 键,我检查 Map2 中是否有一个元素,并通过模式匹配找到差异。有没有一种非常优雅的方法来做到这一点?

回答by elm

Consider the difference between the maps converted into sets of tuples,

考虑转换成元组集的映射之间的差异,

(m1.toSet diff m2.toSet).toMap

回答by Jean Logeart

Try:

尝试:

val diff = (m1.keySet -- m2.keySet) ++ (m2.keySet -- m1.keySet)

diffcontains the elements that are in m1and not in m2and that are in m2and not in m1.

diff包含的中的元素m1,而不是在m2与那些在m2和不在m1

回答by Nikita Zonov

This solution looks like right way:

这个解决方案看起来像正确的方式:

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)

Found it here https://gist.github.com/frgomes/69068062e7849dfe9d5a53bd3543fb81

在这里找到它https://gist.github.com/frgomes/69068062e7849dfe9d5a53bd3543fb81

回答by Nate Whittaker

I think the --operator will do what you're looking for: http://www.scala-lang.org/api/current/index.html#scala.collection.Map@--(xs:scala.collection.GenTraversableOnce[A]):Repr

我认为--运营商会做你正在寻找的:http: //www.scala-lang.org/api/current/index.html#scala.collection.Map@--(xs:scala.collection.GenTraversableOnce[ A]):Repr

Although this will probably only work given the assumption that Map2 is always a subset of Map1...

尽管这可能仅在假设 Map2 始终是 Map1 的子集的情况下才有效......