Merge values in map kotlin

前端 未结 11 1548
慢半拍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().
    0 讨论(0)
  • 2021-02-18 23:58

    I would write something like

    fun Map<String, String>.mergeWith(another: Map<String, String>): Map<String, String> {
      val unionList: MutableMap<String, String> = toMutableMap()
      for ((key, value) in another) {
        unionList[key] = listOfNotNull(unionList[key], value).toSet().joinToString(", ")
      }
      return unionList
    }
    
    val mergedMap = mapA.mergeWith(mapB)
    
    0 讨论(0)
  • 2021-02-19 00:14

    Another approach:

    val mapA = mapOf("Emergency" to "112", "Fire department" to "101", "Police" to "102")
    val mapB = mapOf("Emergency" to "911", "Police" to "102")
    
    val result = mapA.toMutableMap()
    mapB.forEach {
        var value = result[it.key]
        value = if (value == null || value == it.value) it.value else value + ", ${it.value}"
        result[it.key] = value
    }
    

    Or using infix extension function:

    infix fun Map<String, String>.mergeWith(anotherMap: Map<String, String>): Map<String, String> {
        val result = this.toMutableMap()
        anotherMap.forEach {
            var value = result[it.key]
            value = if (value == null || value == it.value) it.value else value + ", ${it.value}"
            result[it.key] = value
        }
        return result
    }
    
    val result = mapA mergeWith mapB
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-19 00:19
        val mapA = mapOf("Emergency" to "112", "Fire department" to "101", "Police" to "102")
        val mapB = mapOf("Emergency" to "911", "Police" to "102")
    
        val result = (mapA.entries + mapB.entries)
            .groupBy({ it.key }, { it.value })
            .mapValues {(_, value) -> 
                value.joinToString(", ")
            }
    
    0 讨论(0)
提交回复
热议问题