Merge values in a map in Kotlin
This article explores different ways to merge values in a map in Kotlin.
1. Using groupBy() function
The idea is to get a distinct list of all mappings and group values by the key such that we get a map where each group key is associated with a list of corresponding values. This would translate to a simple code below using the groupBy() function:
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { val first = mapOf("A" to "0", "B" to "1", "C" to "2") val second = mapOf("A" to "4", "C" to "2") val result = (first.asSequence() + second.asSequence()).distinct() .groupBy({ it.key }, { it.value }) .mapValues { it.value.joinToString(",") } print(result) // {A=0,4, B=1, C=2} } |
2. Using associateWith() function
Another good approach is to collect all keys present in the Map and then associate each key with the set of values using the associateWith() function. Here’s an example of its usage:
|
1 2 3 4 5 6 7 8 9 |
fun main() { val first = mapOf("A" to "0", "B" to "1", "C" to "2") val second = mapOf("A" to "4", "C" to "2") val result = (first.keys + second.keys) .associateWith{ listOf(first[it], second[it]).joinToString() } print(result) // {A=0,4, B=1, C=2} } |
That’s all about merging two maps 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 :)