Compare two Maps in Scala

前端 未结 4 1739
刺人心
刺人心 2021-02-06 00:49

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

4条回答
  •  野性不改
    2021-02-06 01:12

    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

提交回复
热议问题