Compare two Maps in Scala

只谈情不闲聊 提交于 2019-12-20 12:42:07

问题


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?


回答1:


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

(m1.toSet diff m2.toSet).toMap



回答2:


Try:

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

diff contains the elements that are in m1 and not in m2 and that are in m2 and not in m1.




回答3:


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




回答4:


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

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



来源:https://stackoverflow.com/questions/24827462/compare-two-maps-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!