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")
CodePudding user response:
Since the values of a
and the keys of b
will always match, you can do this with a single mapValues
, with the !!
being safe:
val result = a.mapValues { (_, v) -> b[v]!! }
If you hate the appearance of !!
, you can replace that with
?: error("some appropriate error message")
Since it is assumed that b
will always have the values of a
as the key.
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()
CodePudding user response:
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.