0
0
KotlinHow-ToBeginner · 3 min read

How to Merge Two Maps in Kotlin: Simple Examples

In Kotlin, you can merge two maps using the + operator which returns a new map containing entries from both maps. If keys overlap, the values from the second map overwrite those from the first. Alternatively, use toMutableMap() and putAll() to merge maps into a mutable map.
📐

Syntax

To merge two maps in Kotlin, you can use the + operator or the putAll() function on a mutable map.

  • map1 + map2: Returns a new map with entries from both maps. If keys overlap, map2 values overwrite map1.
  • map1.toMutableMap().putAll(map2): Adds all entries from map2 into a mutable copy of map1.
kotlin
val map1 = mapOf("a" to 1, "b" to 2)
val map2 = mapOf("b" to 3, "c" to 4)

val merged1 = map1 + map2
val merged2 = map1.toMutableMap().apply { putAll(map2) }
💻

Example

This example shows how to merge two maps using the + operator and putAll(). It demonstrates how overlapping keys are handled.

kotlin
fun main() {
    val map1 = mapOf("apple" to 1, "banana" to 2)
    val map2 = mapOf("banana" to 3, "cherry" to 4)

    // Using + operator
    val mergedMap = map1 + map2
    println("Merged with + operator: $mergedMap")

    // Using toMutableMap and putAll
    val mutableMergedMap = map1.toMutableMap()
    mutableMergedMap.putAll(map2)
    println("Merged with putAll: $mutableMergedMap")
}
Output
Merged with + operator: {apple=1, banana=3, cherry=4} Merged with putAll: {apple=1, banana=3, cherry=4}
⚠️

Common Pitfalls

One common mistake is expecting the + operator to modify the original map. It actually returns a new map and leaves the originals unchanged. Another pitfall is trying to use putAll() on an immutable map, which causes a compile error.

Always use toMutableMap() before putAll() if you want to modify a map.

kotlin
fun main() {
    val map1 = mapOf("x" to 10)
    val map2 = mapOf("y" to 20)

    // Wrong: trying to modify immutable map
    // map1.putAll(map2) // Error: Unresolved reference

    // Correct:
    val mutableMap = map1.toMutableMap()
    mutableMap.putAll(map2)
    println(mutableMap)
}
Output
{x=10, y=20}
📊

Quick Reference

  • Use map1 + map2 to create a new merged map without changing originals.
  • Use toMutableMap() and putAll() to merge into a mutable map.
  • Overlapping keys take values from the second map.

Key Takeaways

Use the + operator to merge two maps into a new map with second map values overwriting duplicates.
To modify a map by merging, convert it to mutable with toMutableMap() before using putAll().
The original maps remain unchanged when using the + operator.
Overlapping keys in the second map overwrite those in the first map during merge.
Avoid calling putAll() directly on immutable maps to prevent errors.