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