I need merge maps mapA
andmapB
with pairs of \"name\" - \"phone number\" into the final map, sticking together the values for duplicate keys, separated
In Kotlin you could do this:
fun main() {
val map1 = mapOf("A" to 1, "B" to 2)
val map2 = mapOf("A" to 5, "B" to 2)
val result: Map = listOf(map1, map2)
.fold(mapOf()) { accMap, map ->
accMap.merge(map, Int::plus)
}
println(result) // Prints: {A=6, B=4}
}
private fun Map.merge(another: Map, mergeFunction: (V, V) -> V): Map =
toMutableMap()
.apply {
another.forEach { (key, value) ->
merge(key, value, mergeFunction)
}
}