I need merge maps mapA andmapB with pairs of \"name\" - \"phone number\" into the final map, sticking together the values for duplicate keys, separated
mapA
mapB
Here is my approach with universal map-merging helper function:
fun Pair, Map>.merge(merger: (V?, V?) -> R): Map { return (first.keys.asSequence() + second.keys.asSequence()) .associateWith { merger(first[it], second[it]) } } fun main() { val mapA = mapOf("Emergency" to "112", "Fire department" to "101", "Police" to "102") val mapB = mapOf("Emergency" to "911", "Police" to "102") val result = (mapA to mapB).merge { a, b -> listOf(a, b).filterNotNull().distinct().joinToString(",", "(", ")") } println(result) }
Output:
{Emergency=(112,911), Fire department=(101), Police=(102)}