Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a scala Map and would like to test if a certain value exists in the map.

myMap.exists( /*What should go here*/ )
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
767 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...