kotlin merge two maps by overwriting values

Viewed 3481

If I have the below two maps:

val x = mapOf("a" to 10, "b" to 5)
val y = mapOf("a" to 4)
val result = //

How can I get the result to be: {a=4, b=5}? I want the value to be overwritten if the key exists.

2 Answers

val result = x + y does exactly what you need, the second parameter (y) will overwrite the values with the same keys from the first parameter (x)

val result = x.toMutableMap().apply { putAll(y) }
Related