Merge values in map kotlin

前端 未结 11 1706
慢半拍i
慢半拍i 2021-02-18 23:50

I need merge maps mapA andmapB with pairs of \"name\" - \"phone number\" into the final map, sticking together the values for duplicate keys, separated

11条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-18 23:54

    Here is my approach with universal map-merging helper function:

    fun  Pair, Map>.merge(merger: (V?, V?) -> R): Map {
        return (first.keys.asSequence() + second.keys.asSequence())
                .associateWith { merger(first[it], second[it]) }
    }
    
    fun main() {
        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 to mapB).merge { a, b -> 
                listOf(a, b).filterNotNull().distinct().joinToString(",", "(", ")") }
        println(result)
    }
    

    Output:

    {Emergency=(112,911), Fire department=(101), Police=(102)}

提交回复
热议问题