Merge values in map kotlin

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

    How about:

    val unionList = (mapA.asSequence() + mapB.asSequence())
        .distinct()
        .groupBy({ it.key }, { it.value })
        .mapValues { (_, values) -> values.joinToString(",") }
    

    Result:

    {Emergency=112,911, Fire department=101, Police=102}
    

    This will:

    • produce a lazy Sequence of both maps' key-value pairs
    • group them by key (result: Map)
    • map their values to comma-joined strings (result: Map)

提交回复
热议问题