To check if a value exists in a map in Kotlin, you can use the containsValue method. This method returns a boolean value indicating whether the map contains the specified value.
We can check if a value exists in a map in Kotlin using the containsValue method, which returns true if the map contains the specified value and false otherwise.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.containsValue
method to check for a specific value in the map. The containsValue
method returns a boolean value indicating whether the map contains the specified value.println
function.fun main() {
// Declare and initialize a mutable map
val myMap: MutableMap<String, Int> = mutableMapOf(
"one" to 1,
"two" to 2,
"three" to 3
)
// Check if a value exists using containsValue method
val valueExists = myMap.containsValue(2)
// Print the result
println("Does value 2 exist? $valueExists")
}
Does value 2 exist? true
We can check if a value does not exist in a map in Kotlin using the containsValue method, which returns false if the map does not contain the specified value.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.containsValue
method to check for a specific value in the map. The containsValue
method returns a boolean value indicating whether the map contains the specified value.println
function.fun main() {
// Declare and initialize a mutable map
val myMap: MutableMap<String, Int> = mutableMapOf(
"one" to 1,
"two" to 2,
"three" to 3
)
// Check if a value does not exist using containsValue method
val valueExists = myMap.containsValue(4)
// Print the result
println("Does value 4 exist? $valueExists")
}
Does value 4 exist? false
We can check if multiple values exist in a map in Kotlin using the containsValue method, which returns true if the map contains the specified value and false otherwise.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.containsValue
method to check for multiple values in the map. The containsValue
method returns a boolean value indicating whether the map contains the specified value.println
function.fun main() {
// Declare and initialize a mutable map
val myMap: MutableMap<String, Int> = mutableMapOf(
"one" to 1,
"two" to 2,
"three" to 3
)
// Check if multiple values exist using containsValue method
val valueExistsOne = myMap.containsValue(1)
val valueExistsFour = myMap.containsValue(4)
// Print the results
println("Does value 1 exist? $valueExistsOne")
println("Does value 4 exist? $valueExistsFour")
}
Does value 1 exist? true Does value 4 exist? false
In this tutorial, we learned How to Check if a Value Exists in a Map in Kotlin language with well detailed examples.