'In Scala, how to check if a Map contains all entries from another Map?
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.
Solution 1:[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
Solution 2:[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.
Solution 3:[3]
Rex Kerr's answer can be further simplified to
map2.forall{ case (k,v) => map1.get(k).contains(v) }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Rex Kerr |
| Solution 3 | vasigorc |
