Tranforming Structure of Collections

Hello there and thank you for clicking here.

I want to tranform my Data Structure in a functional way.
I start out having a List<Map<String, T>> and I need a Map<String, List<T>>

Background:
The Entries of my List often share the same Key, and I want to accumulate all Entries with the Same Key in a List. That List should still be mapped by the key.

I couldn’t find an elegant solution, this is how I solved it for now:

            val splitted: List<Map, String, T> = ...
            // Map from ID to List of Entities
            val entities: MutableMap<String, MutableList<T>> = mapOf()

            splitted.forEach { entries ->
                entries.forEach { key, value ->
                    entities.getOrPut(key) { mutableListOf() }.add(value)
                }
            }

Hope you can help me out a little

Something like this would work I think

val splitted: List<Map<String, T>> = ...
splitted.flatMap{ it.entries }.groupBy{ it.key }
1 Like

thank you, I’ll test it out. I don’t use flatMap very often, for I often fail to see its potential.
This seems to be a really helpful way of using it

Actually, this is what you want:

splitted.flatMap {
    it.entries
}.groupBy(
    keySelector = { it.key },
    valueTransform = { it.value }
)

@Wasabi375 I was there 5 minutes ago, too. But I took the time to check correctness :stuck_out_tongue:

1 Like

Yeah, maybe I should have done that as well :wink: I normally do, but I did not have an IDE open atm and that’s the easiest way of checking your types are correct. And let’s be honest, waiting for an IDE to start just to answer a simple question like that normally is not worth the time. Should have done it though.

Your IDE is not always open? :scream:

Just kidding, indeed I was already working in the IDE. I wouldn’t have bothered opening it otherwise.

2 Likes

@fatjoe79 @Wasabi375 I’m buffled at how much effort you two put into this, thank you so much!
I’m not even done checking and understanding the code completly :smile:

Let the IDE show you the type of each (sub)expression and identifier in that code. It is very hard to understand without the help of IDE, especially when you are new to Kotlin.

1 Like

Actually, it’s not that much effort. You just write the code snippet in the IDE and then copy it here. And after you spent enough time with kotlin you know the standard library well enough so that you can answer questions like this easily.

As for why I spent time here at all. When I learned to program I had a lot of help from a similar forum like this so I just think it’s fair giving back to the community. And every once in a while there are some interesting discussions here about language design.

2 Likes