Kotlin Tutorials

Kotlin Map containsKey()
Syntax & Examples

Syntax of Map.containsKey()

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.



✐ Examples

1 Check if map contains specified key (present)

In this example,

  • We create a map named map1 containing pairs of numbers and characters.
  • We then check if map1 contains the key 2.
  • As 2 is present in the keys of map1, true is 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 map2 containing pairs of characters and numbers.
  • We then check if map2 contains the key 'd'.
  • As 'd' is not present in the keys of map2, false is 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 map3 containing pairs of strings and numbers.
  • We then check if map3 contains the key 'banana'.
  • As 'banana' is present in the keys of map3, true is 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.