I need merge maps mapA
andmapB
with pairs of \"name\" - \"phone number\" into the final map, sticking together the values for duplicate keys, separated
You can do the following:
(mapA.keys + mapB.keys).associateWith {
setOf(mapA[it], mapB[it]).filterNotNull().joinToString()
}
joinToString()
.I would write something like
fun Map<String, String>.mergeWith(another: Map<String, String>): Map<String, String> {
val unionList: MutableMap<String, String> = toMutableMap()
for ((key, value) in another) {
unionList[key] = listOfNotNull(unionList[key], value).toSet().joinToString(", ")
}
return unionList
}
val mergedMap = mapA.mergeWith(mapB)
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<String, String>.mergeWith(anotherMap: Map<String, String>): Map<String, String> {
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
Here's my solution:
val result = (mapA + (mapB - mapA.keys)).mapValues {
(setOf(it.value) + mapB[it.key]).filterNotNull().joinToString()
}
It creates a map of A plus the values from B that are not in A. Then it maps all values to a set and adds the value from B to that set, ultimately removing all null
values from the set and transforming it into a list, which you can use to create the desired output format.
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.entries + mapB.entries)
.groupBy({ it.key }, { it.value })
.mapValues {(_, value) ->
value.joinToString(", ")
}