Merge values in map kotlin

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

    Here's my solution:

    val result = (mapA + (mapB - mapA.keys)).mapValues {
        (setOf(it.value) + mapB[it.key]).filterNotNull().joinToString()
    }
    

    It creates a map of A plus the values from B that are not in A. Then it maps all values to a set and adds the value from B to that set, ultimately removing all null values from the set and transforming it into a list, which you can use to create the desired output format.

提交回复
热议问题