Skip to main content

How to merge two HashMaps in Kotlin

How to merge two HashMaps in Kotlin.

Here's a step-by-step tutorial on how to merge two HashMaps in Kotlin.

Step 1: Create two HashMaps to be merged

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

Step 2: Create a new HashMap to store the merged result

val mergedMap = HashMap<String, Int>()

Step 3: Add all key-value pairs from the first map to the merged map

mergedMap.putAll(map1)

Step 4: Add all key-value pairs from the second map to the merged map

mergedMap.putAll(map2)

Step 5: Print the merged map

println(mergedMap)

Output:

{A=1, B=2, C=3, D=4}

Step 6: Handle conflicts if the same key exists in both maps

val conflictMap = hashMapOf("A" to 10, "B" to 20)
val mergedMap = HashMap<String, Int>()

for ((key, value) in map1) {
mergedMap[key] = value
}

for ((key, value) in map2) {
if (mergedMap.containsKey(key)) {
// Handle conflict by choosing the value from the second map
mergedMap[key] = map2.getValue(key)
} else {
mergedMap[key] = value
}
}

for ((key, value) in conflictMap) {
if (mergedMap.containsKey(key)) {
// Handle conflict by choosing the value from the conflict map
mergedMap[key] = conflictMap.getValue(key)
} else {
mergedMap[key] = value
}
}

println(mergedMap)

Output:

{A=10, B=20, C=3, D=4}

Step 7: Use the plus operator to merge two HashMaps

val map1 = hashMapOf("A" to 1, "B" to 2)
val map2 = hashMapOf("C" to 3, "D" to 4)
val mergedMap = map1 + map2

println(mergedMap)

Output:

{A=1, B=2, C=3, D=4}

Step 8: Merge multiple HashMaps using the reduce function

val map1 = hashMapOf("A" to 1, "B" to 2)
val map2 = hashMapOf("C" to 3, "D" to 4)
val map3 = hashMapOf("E" to 5, "F" to 6)

val mergedMap = listOf(map1, map2, map3).reduce { acc, map ->
acc.putAll(map)
acc
}

println(mergedMap)

Output:

{A=1, B=2, C=3, D=4, E=5, F=6}

That's it! You've learned how to merge two HashMaps in Kotlin using different approaches. Feel free to use any of these methods based on your specific requirements.