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.
1 2 3 4 | var myMap: Map<String, String> = mapOf("1" to "Mike", "2" to "James", "3" to "Ginger") // returns true println(myMap.containsKey("1")) |
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.
1 2 3 4 | var myMap: Map<String, String> = mapOf("1" to "Mike", "2" to "James", "3" to "Ginger") // returns true println(myMap.contains("2")) |
This one is a bit special. The documentation says the following. Meaning, Kotlin uses this method in the x in map construct.
1 2 3 4 5 6 | /** * Checks if the map contains the given key. This method allows to use the `x in map` syntax for checking * whether an object is contained in the map. */ @kotlin.internal.InlineOnly public inline operator fun <@kotlin.internal.OnlyInputTypes K, V> Map<out K, V>.contains(key: K) : Boolean = containsKey(key) |
Here are examples of the x in map construct that internally uses a Map object’s contains() method.
1 2 3 4 5 6 | var myMap: Map<String, String> = mapOf("1" to "Mike", "2" to "James", "3" to "Ginger") println("2" in myMap) println("1" in myMap) println("4" in myMap) println("Ginger" in myMap) |
When we run the codes, we get the following output.
1 2 3 4 | true true false false |
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.
Last example doesn’t make sense; they should both return true (and they do).
Hi Stephen, you’re correct. I’ll update the comment in code snippet. Thank you!
Hey FYI, you can embed the Kotlin Playground directly into your page, and allow users to edit/run code snippets. I understand if you don’t want that for consistency elsewhere on your site, just a thought.
Thanks for the idea! I’ll look into that.