How to check whether key or value exist in Map?

ScalaDictionaryCollections

Scala Problem Overview


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

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

Scala Solutions


Solution 1 - Scala

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 - Scala

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 - Scala

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 - Scala

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 - Scala

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNabeghView Question on Stackoverflow
Solution 1 - ScalaRex KerrView Answer on Stackoverflow
Solution 2 - ScalaDaniel C. SobralView Answer on Stackoverflow
Solution 3 - ScalailcaveroView Answer on Stackoverflow
Solution 4 - ScalaTomasz NurkiewiczView Answer on Stackoverflow
Solution 5 - ScalarpelegView Answer on Stackoverflow