How to check whether key or value exist in Map?

Nabegh picture Nabegh · May 13, 2012 · Viewed 89.2k times · Source

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

myMap.exists( /*What should go here*/ )

Answer

Rex Kerr picture Rex Kerr · May 13, 2012

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.