To check if a key exists in a map in Kotlin, you can use the containsKey method. This method returns a boolean value indicating whether the map contains the specified key.
We can check if a key exists in a map in Kotlin using the containsKey method, which returns true if the map contains the specified key and false otherwise.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.containsKey
method to check for a specific key in the map. The containsKey
method returns a boolean value indicating whether the map contains the specified key.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 key exists using containsKey method
val keyExists = myMap.containsKey("two")
// Print the result
println("Does key 'two' exist? $keyExists")
}
Does key 'two' exist? true
We can check if a key does not exist in a map in Kotlin using the containsKey method, which returns false if the map does not contain the specified key.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.containsKey
method to check for a specific key in the map. The containsKey
method returns a boolean value indicating whether the map contains the specified key.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 key does not exist using containsKey method
val keyExists = myMap.containsKey("four")
// Print the result
println("Does key 'four' exist? $keyExists")
}
Does key 'four' exist? false
We can check if multiple keys exist in a map in Kotlin using the containsKey method, which returns true if the map contains the specified key and false otherwise.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.containsKey
method to check for multiple keys in the map. The containsKey
method returns a boolean value indicating whether the map contains the specified key.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 keys exist using containsKey method
val keyExistsOne = myMap.containsKey("one")
val keyExistsFour = myMap.containsKey("four")
// Print the results
println("Does key 'one' exist? $keyExistsOne")
println("Does key 'four' exist? $keyExistsFour")
}
Does key 'one' exist? true Does key 'four' exist? false
In this tutorial, we learned How to Check if a Key Exists in a Map in Kotlin language with well detailed examples.