Kotlin Map contains()
Syntax & Examples
Syntax of Map.contains()
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.
✐ 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 use the
in
operator to check if the key2
is present inmap1
. - As
2
is present in the keys ofmap1
,true
is printed to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map1 = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
val containsKey1 = 2 in map1
println(containsKey1)
}
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 use the
in
operator to check if the key'd'
is present inmap2
. - As
'd'
is not present in the keys ofmap2
,false
is printed to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map2 = mapOf('a' to 1, 'b' to 2, 'c' to 3)
val containsKey2 = 'd' in map2
println(containsKey2)
}
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 use the
in
operator to check if the key'banana'
is present inmap3
. - As
'banana'
is present in the keys ofmap3
,true
is printed to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map3 = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
val containsKey3 = "banana" in map3
println(containsKey3)
}
Output
true
Summary
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.