I need merge maps mapA
andmapB
with pairs of "name" - "phone number" into the final map, sticking together the values for duplicate keys, separated by commas. Duplicate values should be added only once.
I need the most idiomatic and correct in terms of language approach.
For example:
val mapA = mapOf("Emergency" to "112", "Fire department" to "101", "Police" to "102")
val mapB = mapOf("Emergency" to "911", "Police" to "102")
The final result should look like this:
{"Emergency" to "112, 911", "Fire department" to "101", "Police" to "102"}
This is my function:
fun mergePhoneBooks(mapA: Map<String, String>, mapB: Map<String, String>): Map<String, String> {
val unionList: MutableMap <String, String> = mapA.toMutableMap()
unionList.forEach { (key, value) -> TODO() } // here's I can't come on with a beatiful solution
return unionList
}
How about:
val unionList = (mapA.asSequence() + mapB.asSequence())
.distinct()
.groupBy({ it.key }, { it.value })
.mapValues { (_, values) -> values.joinToString(",") }
Result:
{Emergency=112,911, Fire department=101, Police=102}
This will:
Sequence
of both maps' key-value pairsMap<String, List<String>
)Map<String, String>
)