Merge values in map kotlin

前端 未结 11 1516
慢半拍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:57

    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)
                }
            }
    

提交回复
热议问题