In Scala, how to check if a Map contains all entri

2020-07-05 06:06发布

问题:

Total newb question. Say I have 2 maps

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

and I want to know if map1 fully contains map2 (extra key/values in map1 are okay), what's a good Scala way to do that?

The best I could come up with was to create my own function:

def doesMapContainMap(map1: Map[_,_], map2: Map[_,_]): Boolean = {
  var matchCount: Int = 0
  map2 foreach {
    entry => {
      if (map1.exists(x => x._1 == entry._1 && x._2 == entry._2)) {
        matchCount += 1;
      }
    }
  }
  // true if the number of matches is equal to the number of elements in map2
  map2.size == matchCount
}

This works (I think), but I'm wondering if there is something better.

回答1:

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


回答2:

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.