Kotlin, Software Development

Three Ways To Check if key exists in Map in Kotlin

This post shows how to check if a key exists in a Map in Kotlin. There are three ways to do this in Kotlin. Note that we are using Kotlin 1.3.

Check Key Exists Using Map containsKey Method

This method of a Map object checks if a key exists using the key itself. Consider the following codes.

Check Key Exists Using Map contains Method

We can use another method to check if a key exists in a Map object using a shorter method name. Consider the following codes.

This one is a bit special. The documentation says the following. Meaning, Kotlin uses this method in the x in map construct.

Here are examples of the x in map construct that internally uses a Map object’s contains() method.

When we run the codes, we get the following output.

In addition, we could see other methods whose purposes are different from the two methods we discussed.

Check Using Other Map Methods

The first method we could use is the get method which accepts a key and returns either the relating value or null.  The key exists in a Map object in Kotlin if the method returns a value. Otherwise, the key does not exist.

Alternatively, we could use the filter methods. However, we craft more those when we use them than with the other methods.

For more information, visit the online Kotlin documentation.

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like