How to combine 2 maps into a third map in Kotlin

2 Answers

0 votes
fun main() {
    val map1 = mapOf("a" to 1, "b" to 2)
	val map2 = mapOf("b" to 999, "c" to 4, "d" to 5)

	val combined = map1 + map2
	
    println(combined) 
}

 
  
/*
run:

{a=1, b=999, c=4, d=5}

*/

 



answered Aug 26, 2025 by avibootz
0 votes
fun main() {
    val map1 = mapOf("a" to 1, "b" to 2)
	val map2 = mapOf("b" to 999, "c" to 4, "d" to 5)

	val combined = (map1.keys + map2.keys).associateWith { key ->
        val v1 = map1[key] ?: 0
        val v2 = map2[key] ?: 0
        v1 + v2
    }
	
    println(combined) 
}

 
  
/*
run:

{a=1, b=1001, c=4, d=5}

*/

 



answered Aug 26, 2025 by avibootz

Related questions

1 answer 96 views
1 answer 106 views
3 answers 111 views
3 answers 178 views
2 answers 113 views
...