Merge values in map kotlin

前端 未结 11 1574
慢半拍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-19 00:14

    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.mergeWith(anotherMap: Map): Map {
        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
    

提交回复
热议问题