'Compose maps using key and value in Kotlin
I have two maps and I want to merge using some rules
val a = mapOf(1 to 101, 2 to 102, 3 to 103)
val b = mapOf(101 to "a", 102 to "b", 103 to "c")
is there a way to merge using values for a and key for b
val result = mapOf(1 to "A", 2 to "b", 3 to "c")
Solution 1:[1]
Since the values of a and the keys of b will always match, you can do this with a single mapValues
val result = a.mapValues { (_, v) -> b.getValue(v) }
getValue can be safely used here since the key v always exist in b as a consequence of our assumption.
In general, if b may not have all the values of a as keys, you can do:
val result = a.entries.mapNotNull { (k, v) -> b[v]?.let { k to it } }.toMap()
This removes the key from the result, if the key's corresponding value in a doesn't exist as a key in b. You can also use this as an alternative if you don't like the !! in the first solution.
mapNotNull and toMap loops through the entries one time each. If that is a problem for you, use asSequence:
a.asSequence().mapNotNull { (k, v) -> b[v]?.let { k to it } }.toMap()
Solution 2:[2]
Since you're sure each value from map a is present in map b, this should be as simple as using mapValues and using the value of that key in map b
a.mapValues { entry ->
b[entry.value]
}
Due to having to edit and redo my answer, @Sweeper beat me to it and provided a more in-depth answer.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
