The syntax of Map.containsKey() function is:
abstract fun containsKey(key: K): Boolean
This containsKey() function of Map returns true if the map contains the specified key.
In this example,
map1
containing pairs of numbers and characters.map1
contains the key 2
.2
is present in the keys of map1
, true
is returned.fun main(args: Array<String>) {
val map1 = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
val containsKey = map1.containsKey(2)
println(containsKey)
}
true
In this example,
map2
containing pairs of characters and numbers.map2
contains the key 'd'
.'d'
is not present in the keys of map2
, false
is returned.fun main(args: Array<String>) {
val map2 = mapOf('a' to 1, 'b' to 2, 'c' to 3)
val containsKey = map2.containsKey('d')
println(containsKey)
}
false
In this example,
map3
containing pairs of strings and numbers.map3
contains the key 'banana'
.'banana'
is present in the keys of map3
, true
is returned.fun main(args: Array<String>) {
val map3 = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
val containsKey = map3.containsKey("banana")
println(containsKey)
}
true
In this Kotlin tutorial, we learned about containsKey() function of Map: the syntax and few working examples with output and detailed explanation for each example.