|
| 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