scala 如何检查Map中是否存在键或值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10567744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check whether key or value exist in Map?
提问by Nabegh
I have a scala Map and would like to test if a certain value exists in the map.
我有一个 Scala 地图,想测试地图中是否存在某个值。
myMap.exists( /*What should go here*/ )
回答by Rex Kerr
There are several different options, depending on what you mean.
有几种不同的选项,具体取决于您的意思。
If you mean by "value" key-value pair, then you can use something like
如果你的意思是“值”键值对,那么你可以使用类似的东西
myMap.exists(_ == ("fish",3))
myMap.exists(_ == "fish" -> 3)
If you mean value of the key-value pair, then you can
如果你的意思是键值对的值,那么你可以
myMap.values.exists(_ == 3)
myMap.exists(_._2 == 3)
If you wanted to just test the key of the key-value pair, then
如果你只想测试键值对的键,那么
myMap.keySet.exists(_ == "fish")
myMap.exists(_._1 == "fish")
myMap.contains("fish")
Note that although the tuple forms (e.g. _._1 == "fish") end up being shorter, the slightly longer forms are more explicit about what you want to have happen.
请注意,尽管元组形式(例如_._1 == "fish")最终变得更短,但稍长的形式更明确地说明了您想要发生的事情。
回答by Daniel C. Sobral
Do you want to know if the valueexists on the map, or the key? If you want to check the key, use isDefinedAt:
您想知道地图上是否存在该值或键?如果要检查密钥,请使用isDefinedAt:
myMap isDefinedAt key
回答by ilcavero
you provide a test that one of the map values will pass, i.e.
您提供了一个地图值将通过的测试,即
val mymap = Map(9->"lolo", 7->"lala")
mymap.exists(_._1 == 7) //true
mymap.exists(x => x._1 == 7 && x._2 == "lolo") //false
mymap.exists(x => x._1 == 7 && x._2 == "lala") //true
The ScalaDocs say of the method "Tests whether a predicate holds for some of the elements of this immutable map.", the catch is that it receives a tuple (key, value) instead of two parameters.
ScalaDocs 说到方法“测试谓词是否适用于这个不可变映射的某些元素。”,问题是它接收一个元组(键,值)而不是两个参数。
回答by Tomasz Nurkiewicz
What about this:
那这个呢:
val map = Map(1 -> 'a', 2 -> 'b', 4 -> 'd')
map.values.toSeq.contains('c') //false
Yields trueif map contains cvalue.
true如果地图包含c值,则产生收益。
If you insist on using exists:
如果你坚持使用exists:
map.exists({case(_, value) => value == 'c'})
回答by rpeleg
Per answers above, note that exists() is significantly slower than contains() (I've benchmarked with a Map containing 5000 string keys, and the ratio was a consistent x100). I'm relatively new to scala but my guess is exists() is iterating over all keys (or key,value tupple) whereas contains uses Map's random access
根据上面的答案,请注意exists() 比contains() 慢得多(我用包含5000 个字符串键的Map 进行了基准测试,比率是一致的x100)。我对 Scala 比较陌生,但我的猜测是 exists() 正在迭代所有键(或键、值元组),而 contains 使用 Map 的随机访问

