Library contents

Kotlin chunked

Partition a sequence into consecutive batches while retaining a shorter final group.

A simple example

chunked

  1. Start with A, B, C
  2. Do this Split into groups of two
  3. Result [A, B] and [C]
The first group is full and the last group keeps the remaining item.

Syntax

Kotlin 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.jar

Pack 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.

From the programval labels = listOf("A", "B", "C", "D", "E")
First output lineA, B
Lesson.kt

fun main() {
    val labels = listOf("A", "B", "C", "D", "E")
    for (batch in labels.chunked(2)) println(batch.joinToString())
}
Output
A, B
C, D
E

Five labels produce two full pairs and one final singleton.

Advertisements

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?

Given7 names · batches of 3
Worked result3

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?

Given8 sets · bundles of 4
Worked result2

What to watch for

The batch size must be positive.

Documentation for chunked