在Scala中,如何检查一个Map是否包含另一个Map的所有条目? [英] In Scala, how to check if a Map contains all entries from another Map?

查看:609
本文介绍了在Scala中,如何检查一个Map是否包含另一个Map的所有条目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

总的newb问题.说我有2张地图

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")

我想知道map1是否完全包含在map2中(map1中的额外键/值还可以),那么Scala的一种好方法是什么?

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.

推荐答案

您可以将Map转换为Set,然后应用subsetOf方法.

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

这篇关于在Scala中,如何检查一个Map是否包含另一个Map的所有条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆