In Scala, how do I check if a Map contains all the records from another Map?

The general question is newb. Say I have 2 cards

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 contains completely map2 (the extra key / values โ€‹โ€‹in map1 are ok), what is a good way for Scala to do this?

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 wonder if there is anything better.

+7
scala scala-collections map
source share
2 answers

You can convert Map to 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 
+15
source share

If you do not want to duplicate your collections,

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

You check everything in map2 by looking at the key in map1 , returning the option and checking what this value is and what should be.

+5
source share

All Articles