scala - 在 Scala 中,如何检查一个 Map 是否包含来自另一个 Map 的所有条目?

标签 scala map scala-collections

总新手问题。说我有 2 张 map

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

我想知道 map1 完全包含 map2(map1 中的额外键/值是可以的),有什么好的 Scala 方法可以做到这一点?

我能想到的最好的办法是创建我自己的函数:
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
}

这有效(我认为),但我想知道是否有更好的方法。

最佳答案

您可以转换 MapSet然后应用 subsetOf方法。

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

关于scala - 在 Scala 中,如何检查一个 Map 是否包含来自另一个 Map 的所有条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25189198/

相关文章:

Spark 中 Scala 的收集效率低下?

scala - 在循环中填充 map [Scala]

scala - scala 2.11 中弃用的 `scala.collection.script` 的替代方案?

scala - Scala DoubleLinkedList 中的当前元素是什么?

scala - 如何编写绑定(bind)集合类型和元素类型的通用 Scala 增强方法?

scala - Scala 中有没有办法从任何 Map 转换为 java.util.Map?

scala - Scala 中的类型推断和模式匹配

ruby - 我如何获得静态谷歌地图的边界?

c++ - 为什么没有 boost::intrusive::map?

从可迭代对象创建集合时,Scala 是否必须转换为 Seq?