Kotlin - How to concatenate two maps?

Viewed 5100

I have two immutable maps, as example:

val a = mapOf("a" to 1, "z" to 1)
val b = mapOf("b" to 1, "a" to 1, "c" to 1)

Is there any elegant way to concatenate these maps and have a single map with all the keys? If it has duplicated keys, I want to replace it with value from B map.

The result should look something like:

mapOf("z" to 1, "b" to 1, "a" to 1, "c" to 1)
1 Answers

simple + operator:

/**
 * 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) }

example:

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)
}
  • output: {a=2, z=1, b=1, c=1}
Related