本文介绍了合并地图科特林中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将带有名称"-电话号码"对的映射mapAmapB合并到最终映射中,将重复键的值粘贴在一起,并用逗号分隔.重复值只能添加一次.就语言方式而言,我需要最惯用和正确的方法.

I need merge maps mapA andmapB with pairs of "name" - "phone number" into the final map, sticking together the values for duplicate keys, separated by commas. Duplicate values should be added only once.I need the most idiomatic and correct in terms of language approach.

例如:

val mapA = mapOf("Emergency" to "112", "Fire department" to "101", "Police" to "102")
val mapB = mapOf("Emergency" to "911", "Police" to "102")

最终结果应如下所示:

{"Emergency" to "112, 911", "Fire department" to "101", "Police" to "102"}

这是我的功能:

fun mergePhoneBooks(mapA: Map<String, String>, mapB: Map<String, String>): Map<String, String> {
    val unionList: MutableMap <String, String> = mapA.toMutableMap()
    unionList.forEach { (key, value) -> TODO() } // here's I can't come on with a beatiful solution

    return unionList
}

推荐答案

怎么样:

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

结果:

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

这将:

  • 同时生成两个地图的键值对的Sequence
  • 按键对它们进行分组(结果:Map<String, List<String>)
  • 将它们的值映射到逗号连接的字符串(结果:Map<String, String>)
  • produce a lazy Sequence of both maps' key-value pairs
  • group them by key (result: Map<String, List<String>)
  • map their values to comma-joined strings (result: Map<String, String>)

这篇关于合并地图科特林中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 20:31