Skip to content

Commit 6b2dd13

Browse files
[KTLN-476] Converting a List of Maps to a Map Grouped by Key in Kotlin (#797)
* Added unit test * fixed code * fixed code * Formatting tweaks --------- Co-authored-by: Brandon Ward <[email protected]>
1 parent 0f46156 commit 6b2dd13

File tree

1 file changed

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

1 file changed

+56
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package com.baeldung.listOfMapsToMaps
2+
3+
import org.junit.jupiter.api.Assertions.assertEquals
4+
import org.junit.jupiter.api.Test
5+
6+
class ListOfMapsToMaps {
7+
8+
val listOfMaps = listOf(
9+
mapOf("name" to "Albert", "age" to "18"),
10+
mapOf("name" to "Naomi", "age" to "26"),
11+
mapOf("name" to "Dru", "age" to "18"),
12+
mapOf("name" to "Steve", "age" to "30")
13+
)
14+
val expectedMap = mapOf(
15+
"name" to listOf("Albert", "Naomi", "Dru", "Steve"),
16+
"age" to listOf("18", "26", "18", "30")
17+
)
18+
19+
@Test
20+
fun `converts list of maps to maps grouped by key using for loop`() {
21+
assertEquals(expectedMap, groupByUsingForLoop(listOfMaps))
22+
}
23+
24+
@Test
25+
fun `converts list of maps to maps grouped by key using groupBy method`() {
26+
val result = listOfMaps
27+
.flatMap { map -> map.entries }
28+
.groupBy({ it.key }, { it.value })
29+
30+
assertEquals(expectedMap, result)
31+
}
32+
33+
@Test
34+
fun `converts list of maps to maps grouped by key using fold method`() {
35+
assertEquals(expectedMap, groupByUsingFoldMethod(listOfMaps))
36+
}
37+
}
38+
39+
fun groupByUsingForLoop(input: List<Map<String, String>>): Map<String, List<String>> {
40+
val result = mutableMapOf<String, MutableList<String>>()
41+
for (map in input) {
42+
for ((key, value) in map) {
43+
result.getOrPut(key) { mutableListOf() }.add(value)
44+
}
45+
}
46+
return result
47+
}
48+
fun groupByUsingFoldMethod(input: List<Map<String, String>>): Map<String, List<String>> {
49+
return input.fold(emptyMap()) { acc, map ->
50+
acc.keys.union(map.keys).associateWith { key ->
51+
acc.getOrDefault(key, emptyList()) + map.getOrDefault(key, "")
52+
}
53+
}
54+
}
55+
56+

0 commit comments

Comments
 (0)