How to check whether key or value exist in Map?

Solution 1:

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.

Solution 2:

Do you want to know if the value exists on the map, or the key? If you want to check the key, use isDefinedAt:

myMap isDefinedAt key

Solution 3:

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.

Solution 4:

What about this:

val map = Map(1 -> 'a', 2 -> 'b', 4 -> 'd')
map.values.toSeq.contains('c')  //false

Yields true if map contains c value.

If you insist on using exists:

map.exists({case(_, value) => value == 'c'})

Solution 5:

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