I have a scala Map and would like to test if a certain value exists in the map.
myMap.exists( /*What should go here*/ )
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With