Kotlin - 如何连接两张地图?

pla*_*oom 3 kotlin

我有两个不可变的地图,例如:

val a = mapOf("a" to 1, "z" to 1)
val b = mapOf("b" to 1, "a" to 1, "c" to 1)
Run Code Online (Sandbox Code Playgroud)

有没有什么优雅的方法来连接这些地图并拥有一个包含所有键的地图?如果它有重复的键,我想用 B 映射中的值替换它。

结果应该类似于:

mapOf("z" to 1, "b" to 1, "a" to 1, "c" to 1)
Run Code Online (Sandbox Code Playgroud)

Nao*_*dgi 8

简单的+运算符

/**
 * Creates a new read-only map by replacing or adding entries to this map from another [map].
 *
 * The returned map preserves the entry iteration order of the original map.
 * Those entries of another [map] that are missing in this map are iterated in the end in the order of that [map].
 */
public operator fun <K, V> Map<out K, V>.plus(map: Map<out K, V>): Map<K, V> =
    LinkedHashMap(this).apply { putAll(map) }
Run Code Online (Sandbox Code Playgroud)

例子:

fun main(args: Array<String>) {
    val a = mapOf("a" to 1, "z" to 1)
    val b = mapOf("b" to 1, "a" to 2, "c" to 1)
    val c = a+b
    println(c)
}
Run Code Online (Sandbox Code Playgroud)
  • 输出:{a=2, z=1, b=1, c=1}