Merge values in map kotlin

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

    You can do the following:

    (mapA.keys + mapB.keys).associateWith {
        setOf(mapA[it], mapB[it]).filterNotNull().joinToString()
    }
    
    1. put all keys in a set
    2. iterate over that set and and associate each element with the set of values
    3. remove the null values from the value set
    4. concatenate the elements in the value list using joinToString().

提交回复
热议问题