In Scala, how to check if a Map contains all entries from another Map?

前端 未结 2 2114
暗喜
暗喜 2021-02-19 11:00

Total newb question. Say I have 2 maps

val map1 = Map(\"ram\"->\"2gb\", \"size\"->\"15\", \"color\"->\"red\", \"fruit\"->\"strawberry\")
val map2 =          


        
相关标签:
2条回答
  • 2021-02-19 11:37

    You can convert a Map to a Set and then apply the subsetOf method.

    val map1 = Map("ram"->"2gb", "size"->"15", "color"->"red", "fruit"->"strawberry")
    val map2 = Map("ram"->"2gb", "size"->"15", "color"->"red")
    
    map2.toSet subsetOf map1.toSet // res0: Boolean = true
    
    0 讨论(0)
  • 2021-02-19 11:44

    If you don't want to duplicate your collections,

    map2.forall{ case (k,v) => map1.get(k).exists(_ == v) }
    

    You check everything in map2 by looking up the key in map1, returning an option, and checking that the value is there and what it should be.

    0 讨论(0)
提交回复
热议问题