I need merge maps mapA
andmapB
with pairs of \"name\" - \"phone number\" into the final map, sticking together the values for duplicate keys, separated
Another approach:
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.toMutableMap()
mapB.forEach {
var value = result[it.key]
value = if (value == null || value == it.value) it.value else value + ", ${it.value}"
result[it.key] = value
}
Or using infix extension function:
infix fun Map.mergeWith(anotherMap: Map): Map {
val result = this.toMutableMap()
anotherMap.forEach {
var value = result[it.key]
value = if (value == null || value == it.value) it.value else value + ", ${it.value}"
result[it.key] = value
}
return result
}
val result = mapA mergeWith mapB