How to check whether key or value exist in Map?

99,915

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

Share:
99,915
Nabegh
Author by

Nabegh

Updated on May 17, 2020

Comments

  • Nabegh
    Nabegh almost 4 years

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

    myMap.exists( /*What should go here*/ )
    
  • Luigi Plinge
    Luigi Plinge almost 12 years
    values creates a new Iterable so you probably are better off with map.valuesIterator.contains('c') (although that's not as easy as map.exists(_._2 == 'c')!)
  • Dave Griffith
    Dave Griffith almost 12 years
    Also worth saying that for testing existence of a key, the library provides myMap.contains("fish")
  • Rex Kerr
    Rex Kerr almost 12 years
    @DaveGriffith - Indeed. I was just using "exists", but that one's important enough (since it is the one you should use) to add in. I've amended the answer accordingly.