Kotlin chunked
Partition a sequence into consecutive batches while retaining a shorter final group.
A simple example
chunked
- Start with A, B, C
- Do this Split into groups of two
- Result [A, B] and [C]
Syntax
labels.chunked(2)
Run these examples in Kotlin
Save one example at a time as Lesson.kt. Use Kotlin 2.2 on JDK 21.
kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jarPack mailing labels in groups of two
A mailroom prints multiple labels per sheet. Process the list in small batches and verify how the final sheet is handled when fewer labels remain than the normal batch size.
fun main() {
val labels = listOf("A", "B", "C", "D", "E")
for (batch in labels.chunked(2)) println(batch.joinToString())
}
A, B C, D E
Five labels produce two full pairs and one final singleton.
Batch badge printing
A club sends seven names to a printer that takes three names per batch. Split the records into consecutive batches and retain a partial final batch. How many batches go to the desk?
Bundle class handouts
A classroom has eight sets of papers to bundle into fours. Split the records into consecutive batches and retain a partial final batch. How many batches go to the desk?
What to watch for
The batch size must be positive.