Sling Academy
Home/Kotlin/Merging Two Maps in Kotlin

Merging Two Maps in Kotlin

Last updated: November 30, 2024

When working with collections in Kotlin, particularly with Maps, you might find yourself needing to combine or merge two maps together. This is a common requirement and can be accomplished in several straightforward ways with Kotlin's rich collection library. In this article, we will demonstrate different methods to merge two maps in Kotlin.

Merging Maps in Kotlin

1. Using the plus Operator

The simplest way to merge two maps is by using the plus operator. The resulting map will contain all entries of the first map and any new entries from the second map. If both maps have the same key, the entry from the second map will be in the resulting map:

val map1 = mapOf("A" to 1, "B" to 2, "C" to 3)
val map2 = mapOf("B" to 10, "D" to 4)

val result = map1 + map2
// Prints: {A=1, B=10, C=3, D=4}
println(result)

2. Using the putAll Function

Another approach is to use the putAll function. This method requires a mutable map because putAll modifies the existing map, unlike the plus operator:

val map1 = mutableMapOf("A" to 1, "B" to 2, "C" to 3)
val map2 = mapOf("B" to 10, "D" to 4)

map1.putAll(map2)
// Prints: {A=1, B=10, C=3, D=4}
println(map1)

3. Merging Using forEach Loop

You can also merge maps by iterating in a forEach loop. This method is useful when you need custom behavior for merging:

val map1 = mutableMapOf("A" to 1, "B" to 2, "C" to 3)
val map2 = mapOf("B" to 10, "D" to 4)

map2.forEach { (key, value) ->
    map1[key] = value
}
// Prints: {A=1, B=10, C=3, D=4}
println(map1)

4. Merging By Creating a Custom Function

In complex scenarios where you need specific merging logic, it's helpful to create a custom function. Here's an example where we decide how to merge values for keys that exist in both maps:

fun  mergeMaps(map1: Map, map2: Map, mergeFunction: (V, V) -> V): Map {
    val result = map1.toMutableMap()
    map2.forEach { (key, value) ->
        result[key] = if (result.containsKey(key)) {
            mergeFunction(result[key]!!, value)
        } else {
            value
        }
    }
    return result
}

val map1 = mapOf("A" to 1, "B" to 2, "C" to 3)
val map2 = mapOf("B" to 10, "D" to 4)

val mergedMap = mergeMaps(map1, map2) { v1, v2 -> v1 + v2 }
// Prints: {A=1, B=12, C=3, D=4}
println(mergedMap)

Conclusion

Whether you're using Kotin's built-in operators and functions to quickly merge maps or creating a custom solution for more complex needs, Kotlin provides great flexibility. The choice of method depends on your specific requirements, such as whether you need the original data unchanged or whether you need specialized merging logic.

Next Article: Kotlin: Grouping and Counting Elements in Maps

Previous Article: Iterating Through Maps in Kotlin: Keys, Values, and Entries

Series: Kotlin Collections

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin