This article explores different ways to check if a key exists in a Kotlin Map.

1. Using containsKey() function

The standard solution to find a key in a Map is using the containsKey() function. It returns true if the map contains an entry for the specified key. If the key represents a custom object, remember to override the equals and hashCode method for that class.

Download Code

2. Using any() function

Another option is to get the collection of the keys contained in the map with map.keys and simply search the specified key in the collection using the any() function, as shown below:

Download Code

3. Using indexing operator

If the map doesn’t contain any null value, we can do something like below. In Kotlin, replace get() with the indexing operator.

Download Code

That’s all about checking if a key exists in a Kotlin Map.