To merge two maps in Kotlin, you can use the plus operator to create a new map that combines the contents of both maps. This method provides a concise and convenient way to merge maps.
We can merge two maps in Kotlin using the plus operator, which creates a new map that includes all key-value pairs from both maps.
For example,
map1
and map2
with some key-value pairs. In this example, both maps have string keys and integer values.mergedMap
that combines the contents of map1
and map2
using the plus operator.println
function to verify the merge.fun main() {
// Declare and initialize two maps
val map1 = mapOf("one" to 1, "two" to 2)
val map2 = mapOf("three" to 3, "four" to 4)
// Merge the maps using the plus operator
val mergedMap = map1 + map2
// Print the merged map
println("Merged Map: $mergedMap")
}
Merged Map: {one=1, two=2, three=3, four=4}
We can merge two maps in Kotlin and handle overlapping keys using the plus operator. If a key exists in both maps, the value from the second map will overwrite the value in the first map.
For example,
map1
and map2
with some key-value pairs. In this example, both maps have string keys and integer values, and there is an overlapping key.mergedMap
that combines the contents of map1
and map2
using the plus operator. The value from map2
will overwrite the value from map1
for overlapping keys.println
function to verify the merge.fun main() {
// Declare and initialize two maps with overlapping keys
val map1 = mapOf("one" to 1, "two" to 2)
val map2 = mapOf("two" to 22, "three" to 3)
// Merge the maps using the plus operator
val mergedMap = map1 + map2
// Print the merged map
println("Merged Map: $mergedMap")
}
Merged Map: {one=1, two=22, three=3}
We can also merge two mutable maps in Kotlin using the putAll method, which adds all key-value pairs from one map to another.
For example,
map1
and map2
with some key-value pairs. In this example, both maps have string keys and integer values.putAll
method to add all key-value pairs from map2
to map1
.println
function to verify the merge.fun main() {
// Declare and initialize two mutable maps
val map1 = mutableMapOf("one" to 1, "two" to 2)
val map2 = mutableMapOf("three" to 3, "four" to 4)
// Merge map2 into map1 using putAll
map1.putAll(map2)
// Print the merged map
println("Merged Map: $map1")
}
Merged Map: {one=1, two=2, three=3, four=4}
In this tutorial, we learned How to Merge Two Maps in Kotlin language with well detailed examples.