14

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.

elm
  • 20,117
  • 14
  • 67
  • 113
Thomas
  • 181
  • 2
  • 5

3 Answers3

23

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
8

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.

Rex Kerr
  • 166,841
  • 26
  • 322
  • 407
1

Rex Kerr's answer can be further simplified to

map2.forall{ case (k,v) => map1.get(k).contains(v) }
vasigorc
  • 882
  • 11
  • 22