Merge values in map kotlin

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

    A more generic approach (as this post comes up when searching for kotlin and merging maps):

    fun  Map.mergeReduce(other: Map, reduce: (key: K, value1: V1?, value2: V2?) -> R): Map =
        (this.keys + other.keys).associateWith { reduce(it, this[it], other[it]) }
    

    It allows for Maps with different types of values to be merged, increased freedom with a custom reducer and increased readability.

    Your problem can than be solved as:

    mapA.mergeReduce(mapB) { _, value1, value2 -> listOfNotNull(value1, value2).joinToString(", ") }
    

提交回复
热议问题