Hi! :wave: I am trying to "flatten" a `List<Map...
# getting-started
t
Hi! 👋 I am trying to "flatten" a
List<Map<String, List<T>>>
to
Map<String, List<T>>
. If the original list of maps contain two maps containing the same String key, the lists should be merged / concatenated. I finding it hard to achieve this, could anyone nudge me in the right direction?
a
First look into how to merge two maps like that Then just use list reduce to do it for a whole list For the two maps you could have map
a
as mutableMap and then
forEach
entry in map
b
merge
it onto map
a
. https://pl.kotl.in/0ZLLykh1n
m
Copy code
fun <T> List<Map<String, List<T>>>.flatten(): Map<String, List<T>> {
    return flatMap { it.entries }           // List<Map.Entry<String, List<T>>
        .groupBy { it.key }                 // Map<String, List<Map.Entry<String, List<T>>>
        .mapValues { (_, value: List<Map.Entry<String, List<T>>>) -> 
            value.flatMap { it.value }      // List<T>
        }
}
Feel free to remove some type annotations/comments
👍 1
t
Thanks a bunch @Alowaniak and @molikuner! Impressed by the solutions and swift reply