Search code examples
kotlin

Group one list element into multiple groups ("indexBy")


I am looking for a way to group elements of a list in kotlin in a ways that one element can reside in multiple of the resulting groups.

Let's say the elements of the list look like this:

data class Member (
    val name: String,
    val roles: List<String> = mutableListOf()
)

I'd like to do:

listOf(
  Member(name = "Name One", roles = listOf("A", "B")),
  Member(name = "Name Two", roles = listOf("A", "C"))
).groupBy{ it.roles }

And the result should be a Map<String, List<Member>> containing the objects (simplified by the name in this case):

Key Value
A ["Name One", "Name Two"]
B ["Name One"]
C ["Name Two"]

Is this possible in the kotlin standard lib or do i have to implement it myself? Just to be sure: The question is about "is there already something?". Of course i read all the documentation first but i'm not sure if i missed something.

I am explicitly not asking for a custom implementation.


Solution

  • I think there is no variant of groupBy that would have this effect, because conceptually it's about splitting the iterable/collection into distinct groups, so I guess there is no way one element can end up in multiple groups.

    Even the Grouping abstraction itself assumes the existence of a key selector that gives a single key for each element, which makes it incompatible with your use case.

    You'll probably have to implement your own.