Collections -> I have a SizedIterable list with...
# announcements
v
Collections -> I have a SizedIterable list with dynamic content that came from an inner join statement. How can I map a new list with grouped "father" fields, and add an inner list with child records of each father?
k
Are you talking about Kotlin? What's a
SizedIterable
or an inner join?
v
Sorry, inner join is just to draw the context, also SizedIterable is something from the framwork but it coud be any Interator. I endend up with this but I think there is a cleaner way:
Copy code
fun main() {
    val a = Person("jhon", "arm")
    val b = Person("jhon", "shoulder")
    val c = Person("marie", "leg")

    val list = listOf(a, b, c) //this is what I initially have
    val groupedLis = list.groupBy {
        it.name
    }
    
    val aggregation = mutableListOf<UniquePerson>() // this is what I want
    groupedLis.forEach { t, u ->
        val tattos = mutableListOf<String>()
        u.forEach {
            tattos.add(it.tatto)
        }
        val uniquePerson = UniquePerson(t, tattos)
        aggregation.add(uniquePerson)
    }
}

data class Person(val name: String, val tatto: String)
data class UniquePerson(val name: String, val tattos: List<String>)
k
Copy code
val aggregation = list.groupBy { it.name }.map { (name, persons) -> UniquePerson(name, persons.map { it.tatto }) }
(its tattoo btw)
v
Thanks! a lot of learning today. Does this scale well? Apart from groupBy is there any other way with better performance to do this? Maybe sequences?
k
I don't think there's a better way to do this, you do need to keep all persons in a temporary collection anyway, you can't start creating `UniquePerson`s before having checked all persons.
There's a lazy form of
groupBy
simlar to sequences but for maps:
groupingBy
which returns a
Grouping
. It doesn't have a
map
function defined on it though, because you need the intermediate collection anyway.
✔️ 1