Is there a built-in way to do something like `grou...
# announcements
n
Is there a built-in way to do something like
groupBy { }
, but only group on elements where the key is contiguous? Say I have a
List<Sample>
where sample is
class Sample(duration: Int)
. I need something like a
List<List<Sample>>
, where samples are grouped by duration, but not reordered. If durations are 100, 100, 100, 200 and 100, that should be three groups, not two.
p
You can do that with
fold
. Not the simplest use of it, but doable… https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/fold.html
n
Thanks. That's kind of what I have right now, but I have the feeling that something better could be done.
Copy code
samples.fold(mutableListOf<MutableList<Sample>>()) { groups, sample ->
    val duration = groups.lastOrNull()?.lastOrNull()?.duration
    if (sample.duration == duration) {
        groups.last().add(sample)
    } else {
        groups.add(mutableListOf(sample))
    }
    groups
}
p
yeah, I can’t see a better alternative with this approach… 😬
d
This was considered as part of sliding window functions, but not implemented as too niche
k
I found this in my util library for advent of code