Kotlin Map containsKey()
Syntax & Examples
Syntax of Map.containsKey()
The syntax of Map.containsKey() function is:
abstract fun containsKey(key: K): BooleanThis containsKey() function of Map returns true if the map contains the specified key.
✐ Examples
1 Check if map contains specified key (present)
In this example,
- We create a map named
map1containing pairs of numbers and characters. - We then check if
map1contains the key2. - As
2is present in the keys ofmap1,trueis returned. - We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map1 = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
val containsKey = map1.containsKey(2)
println(containsKey)
}Output
true
2 Check if map contains specified key (not present)
In this example,
- We create a map named
map2containing pairs of characters and numbers. - We then check if
map2contains the key'd'. - As
'd'is not present in the keys ofmap2,falseis returned. - We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map2 = mapOf('a' to 1, 'b' to 2, 'c' to 3)
val containsKey = map2.containsKey('d')
println(containsKey)
}Output
false
3 Check if map contains specified key (present)
In this example,
- We create a map named
map3containing pairs of strings and numbers. - We then check if
map3contains the key'banana'. - As
'banana'is present in the keys ofmap3,trueis returned. - We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map3 = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
val containsKey = map3.containsKey("banana")
println(containsKey)
}Output
true
Summary
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.