holgerbrandl
10/31/2024, 3:23 PMfun <T, K> List<T>.chunkBy(selector: (T) -> K): List<List<T>> {
val result = mutableListOf<MutableList<T>>()
var lastKey: K? = null
for (item in this) {
if (selector(item) != lastKey) result.add(mutableListOf(item)).also { lastKey = selector(item) }
else result.last().add(item)
}
return result
}
data class Person(val age: Int)
val persons = listOf(Person(23), Person(12), Person(23), Person(23), Person(22))
val chunkBy = persons.chunkBy { it.age }
but maybe its already part of stdlib?jw
10/31/2024, 3:31 PMjw
10/31/2024, 3:32 PMjw
10/31/2024, 3:32 PMjw
10/31/2024, 3:35 PMjw
10/31/2024, 3:38 PMchunkedBy
. It's almost like a runningGroupBy
or something.holgerbrandl
10/31/2024, 7:39 PMAdam S
10/31/2024, 8:49 PM.chunked()
, but with a predicate https://youtrack.jetbrains.com/issue/KT-41648kevin.cianfarini
11/07/2024, 6:08 PMgroupBy
and then grabbing the values from the resulting map?
val peopleByAge = persons.groupBy { it.age }.values
jw
11/07/2024, 6:46 PMlistOf(Person(23), Person(12), Person(23), Person(23), Person(22))
should produce
[
[Person(23)],
[Person(12)],
[Person(23), Person(23)],
[Person(22)],
]
jw
11/07/2024, 6:47 PM