I need merge maps mapA
andmapB
with pairs of \"name\" - \"phone number\" into the final map, sticking together the values for duplicate keys, separated
A more generic approach (as this post comes up when searching for kotlin and merging maps):
fun Map.mergeReduce(other: Map, reduce: (key: K, value1: V1?, value2: V2?) -> R): Map =
(this.keys + other.keys).associateWith { reduce(it, this[it], other[it]) }
It allows for Maps with different types of values to be merged, increased freedom with a custom reducer and increased readability.
Your problem can than be solved as:
mapA.mergeReduce(mapB) { _, value1, value2 -> listOfNotNull(value1, value2).joinToString(", ") }