Skip to content

Commit 44d19c4

Browse files
authored
Merge pull request #802 from tapankavasthi/dev/tavasthi-ktln-478
KTLN-478: Merging Two Maps in Kotlin
2 parents b31c75c + 69d2d0a commit 44d19c4

File tree

1 file changed

+62
-0
lines changed
  • core-kotlin-modules/core-kotlin-collections-map/src/test/kotlin/com/baeldung/mergemap

1 file changed

+62
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package com.baeldung.mergemap
2+
3+
import org.junit.jupiter.api.Assertions.assertEquals
4+
import org.junit.jupiter.api.Test
5+
6+
class MergeMapUnitTest {
7+
8+
@Test
9+
fun `Return new merged map after merging two maps with plus operator`() {
10+
val map1 = mapOf("a" to 1, "b" to 2)
11+
val map2 = mapOf("b" to 3, "c" to 4)
12+
13+
val mergedMap = map1 + map2
14+
15+
assertEquals(mapOf("a" to 1, "b" to 3, "c" to 4), mergedMap)
16+
}
17+
18+
@Test
19+
fun `First map contains result of merging with second map using the putAll method`() {
20+
val map1 = mutableMapOf("a" to 1, "b" to 2)
21+
val map2 = mapOf("b" to 3, "c" to 4)
22+
23+
map1.putAll(map2)
24+
25+
assertEquals(mapOf("a" to 1, "b" to 3, "c" to 4), map1)
26+
}
27+
28+
@Test
29+
fun `Return new merged map after merging two maps with plus assign operator`() {
30+
val map1 = mutableMapOf("a" to 1, "b" to 2)
31+
val map2 = mapOf("b" to 3, "c" to 4)
32+
33+
map1 += map2
34+
35+
assertEquals(mapOf("a" to 1, "b" to 3, "c" to 4), map1)
36+
}
37+
38+
@Test
39+
fun `Return new merged map after merging two maps using assicateWith function`() {
40+
val map1 = mapOf("a" to 1, "b" to 2)
41+
val map2 = mapOf("b" to 3, "c" to 4)
42+
43+
val mergedMap = (map1.keys + map2.keys).associateWith {
44+
key -> map2[key] ?: map1[key]!!
45+
}
46+
47+
assertEquals(mapOf("a" to 1, "b" to 3, "c" to 4), mergedMap)
48+
}
49+
50+
@Test
51+
fun `Second map contains result of merging two maps using Java Map merge function`() {
52+
val map1 = mutableMapOf("a" to 1, "b" to 2)
53+
val map2 = mapOf("b" to 3, "c" to 4)
54+
55+
map2.forEach { (key, value) ->
56+
map1.merge(key, value) { oldVal, newVal -> newVal * oldVal }
57+
}
58+
59+
assertEquals(mapOf("a" to 1, "b" to 6, "c" to 4), map1)
60+
}
61+
62+
}

0 commit comments

Comments
 (0)