Search code examples
javakotlin

Merge values in map kotlin


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
}

Solution

  • 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:

    • produce a lazy Sequence of both maps' key-value pairs
    • group them by key (result: Map<String, List<String>)
    • map their values to comma-joined strings (result: Map<String, String>)