Does kotlin have an elegant equivalent to `chunked...
# announcements
a
Does kotlin have an elegant equivalent to
chunked
, where the partial window is at the start? eg with list
[1, 2, 3, 4, 5, 6, 7, 8]
,
chunked
gives
[[1, 2, 3], [4, 5, 6], [7, 8]]
, but I want
[[1, 2], [3, 4, 5], [6, 7, 8]]
. Or do I have to modulo myself and chunk when I know it's a multiple of my chunk window?
I was thinking about that, but then the entries within each group would also be reversed
I have
Copy code
val rows: MutableList<View> = mutableListOf()

val firstRowCount = contents.size % 4
if (firstRowCount > 0) {
  rows.add(createRow(contents.take(firstRowCount)))
}
rows.addAll(contents.drop(firstRowCount).chunked(4) { createRow(it) })
which isn't too bad, but I was hoping for a more stream-like solution
i
You'd have to know the end of the stream to know where to do the splitting if you're not counting from the beginning. That's not conducive for streaming APIs
a
Right, my request did not make sense. Thanks!
n
You could define such a thing yourself, by asking the iterable if it knows its own size
there isn't an elegant way to do it if you're actually streaming, but if you want it to work for iterables that come from sized containers it is possible
Actually, sorry, even better
just implement your function taking
Collection<T>
instead of
Iterable<T>
👍 1
collections know their size and are also iterables
so you would be able to do things like
for sublist in rows.chunked(3))
or whatever