Reverse a map in Kotlin
This article explores different ways to reverse a map in Kotlin.
1. Using associate() function
A simple solution is to use the associate() function, which returns a map containing key-value pairs provided by the transform function applied to the given sequence elements.
|
1 2 3 4 5 6 7 |
fun main() { val mutableMap: Map<Int, String> = mutableMapOf(1 to "one", 2 to "two", 3 to "three") val reverseMap: Map<String, Int> = mutableMap.entries.associate { (key, value) -> value to key } print(reverseMap) // {one=1, two=2, three=3} } |
2. Using associateBy() function
Alternatively, you can use the associateBy() function that returns a map containing the elements from the given sequence indexed by the key returned from the keySelector function applied to each element.
|
1 2 3 4 5 6 7 |
fun main() { val mutableMap: Map<Int, String> = mutableMapOf(1 to "one", 2 to "two", 3 to "three") val reverseMap: Map<String, Int> = mutableMap.entries.associateBy({ it.value }) { it.key } print(reverseMap) // {one=1, two=2, three=3} } |
3. Using map() function
Another simple approach is to use the map() function to invert the mapping of a map. Here’s an example of its usage:
|
1 2 3 4 5 6 7 |
fun main() { val mutableMap: Map<Int, String> = mutableMapOf(1 to "one", 2 to "two", 3 to "three") val reverseMap: Map<String, Int> = mutableMap.map { (key, value) -> value to key }.toMap() print(reverseMap) // {one=1, two=2, three=3} } |
4. Using also() function
Finally, you can write your own code to reverse a map. This can be easily done with combination of also() and forEach() function.
|
1 2 3 4 5 6 7 8 9 |
fun main() { val mutableMap: Map<Int, String> = mutableMapOf(1 to "one", 2 to "two", 3 to "three") val reverseMap: Map<String, Int> = mutableMapOf<String, Int>().also { mutableMap.forEach { (k, v) -> it[v] = k } } print(reverseMap) // {one=1, two=2, three=3} } |
That’s all about reversing 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 :)