Determine if a value exists in a Kotlin Map
This article explores different ways to check if a value exists in a Map in Kotlin.
1. Using containsValue() function
The recommended solution to find a value in a Map is using the containsValue() function. It returns true if the map contains one or more keys corresponding to the specified value. If the value is a custom object, don’t forget to override the equals and hashCode method.
|
1 2 3 4 5 6 7 8 9 |
fun main() { val map: MutableMap<Char, Int> = mutableMapOf() for (i in 65..90) { map[i.toChar()] = i } val value = 70 val exist = map.containsValue(value) println(exist) // true } |
2. Using any() function
Another plausible way involves getting the mutable collection of the values contained in the map and searching the specified value in it. Here’s a working example:
|
1 2 3 4 5 6 7 8 9 |
fun main() { val map: MutableMap<Char, Int> = mutableMapOf() for (i in 65..90) { map[i.toChar()] = i } val value = 70 val exist = map.values.any { it == value } println(exist) // true } |
3. Using Loop
Finally, we can write custom logic to determine if a value exists in a Map. Here’s how the code would look like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
fun main() { val map: MutableMap<Char, Int> = mutableMapOf() for (i in 65..90) { map[i.toChar()] = i } val value = 70 var exist = false for (v in map.values) { if (v == value) { exist = true break } } println(exist) // true } |
That’s all about checking if a value exists in a Map in Kotlin.
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 :)