How to check if a key or value exists on a map?

I have a scala map and want to check if any value exists on the map.

myMap.exists( /*What should go here*/ ) 
+58
collections dictionary scala
May 12 '12 at 22:07
source share
5 answers

Depending on what you mean, there are several different options.

If you mean a key-value "value" pair, you can use something like

 myMap.exists(_ == ("fish",3)) myMap.exists(_ == "fish" -> 3) 

If you mean the value of a key-value pair, you can

 myMap.values.exists(_ == 3) myMap.exists(_._2 == 3) 

If you just want to check the key of a key-value pair, then

 myMap.keySet.exists(_ == "fish") myMap.exists(_._1 == "fish") myMap.contains("fish") 

Note that although tuple forms (for example, _._1 == "fish" ) end shorter, slightly longer forms more clearly express what you want to execute.

+88
May 13 '12 at 4:39 a.m.
source share

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

 myMap isDefinedAt key 
+13
May 14 '12 at 2:33 a.m.
source share

you provide a check that one of the values โ€‹โ€‹of the card 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 

ScalaDocs talk about the method "Checks if the predicate for some elements of this immutable mapping". The trick is that it gets a tuple (key, value) instead of two parameters.

+7
May 12 '12 at 10:18
source share

How about this:

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

Valid values โ€‹โ€‹are true if the map contains a value of c .

If you insist on using exists :

 map.exists({case(_, value) => value == 'c'}) 
+5
May 12, '12 at 22:19
source share

In the answers above, note that exists () is much slower than contains () (I compared with a map containing 5000 string keys, and the ratio was consistent x100). I am relatively new to scala, but my assumption exists () iterates all the keys (or the key, the tupple value), while it contains the use of random access to the map

0
May 17 '16 at 5:13
source share



All Articles