Merge values in map kotlin

前端 未结 11 1573
慢半拍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条回答
  •  Happy的楠姐
    2021-02-18 23:58

    I would write something like

    fun Map.mergeWith(another: Map): Map {
      val unionList: MutableMap = toMutableMap()
      for ((key, value) in another) {
        unionList[key] = listOfNotNull(unionList[key], value).toSet().joinToString(", ")
      }
      return unionList
    }
    
    val mergedMap = mapA.mergeWith(mapB)
    

提交回复
热议问题