Check if a key exists in a Kotlin Map
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.
|
1 2 3 4 5 6 7 8 |
fun main() { val map: MutableMap<String, Int> = mutableMapOf(Pair("A", 1), Pair("B", 2), Pair("C", 3), Pair("D", 4), Pair("E", 5)) val key = "B" val hasKey = map.containsKey(key) println(hasKey) // true } |
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:
|
1 2 3 4 5 6 7 8 |
fun main() { val map: MutableMap<String, Int> = mutableMapOf(Pair("A", 1), Pair("B", 2), Pair("C", 3), Pair("D", 4), Pair("E", 5)) val key = "B" val hasKey = map.keys.any { it == key } println(hasKey) // true } |
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.
|
1 2 3 4 5 6 7 8 |
fun main() { val map: MutableMap<String, Int> = mutableMapOf(Pair("A", 1), Pair("B", 2), Pair("C", 3), Pair("D", 4), Pair("E", 5)) val key = "B" val hasKey = map[key] != null println(hasKey) // true } |
That’s all about checking if a key exists in a Kotlin Map.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)