Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether key or value exist in Map?

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

myMap.exists( /*What should go here*/ )
like image 657
Nabegh Avatar asked May 12 '12 22:05

Nabegh


People also ask

How do you compare a key and a value on a map?

Compare Entry: Entry is a key-value pair. We can compare two HashMap by comparing Entry with the equals() method of the Map returns true if the maps have the same key-value pairs that mean the same Entry.

How do you check if a key exists in a map JavaScript?

The Map.has() method in JavaScript is used to check whether an element with a specified key exists in a map or not. It returns a boolean value indicating the presence or absence of an element with a specified key in a map.


3 Answers

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.

like image 199
Rex Kerr Avatar answered Oct 06 '22 12:10

Rex Kerr


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 
like image 33
Daniel C. Sobral Avatar answered Oct 06 '22 14:10

Daniel C. Sobral


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.

like image 33
ilcavero Avatar answered Oct 06 '22 13:10

ilcavero