chunked
- Kotlin course
- Advanced
- Lesson 56/83
- 5 min
Learn chunking with chunked.
chunked
chunked splits a collection into consecutive, non-overlapping chunks. Unlike windowed, chunks do not slide.
Example: listOf(1, 2, 3, 4, 5).chunked(2) returns [[1, 2], [3, 4], [5]]. The last chunk may be smaller. With chunked(2) { it.sum() } you can transform each chunk into a value. It is ideal for paging and grouping.
chunked transform
Passing a lambda to chunked transforms each chunk. The result is a list; no intermediate List is built.
Example: listOf(1, 2, 3, 4, 5, 6).chunked(3) { it.joinToString("") }. This returns ["123", "456"]. joinToString turns each chunk into a string. This pattern is useful for grouping numbers into strings.
Practice Group sums with chunked
In main assign the result of listOf(1, 2, 3, 4, 5, 6).chunked(3) { it.sum() } to a variable and print it with println.
Starter code
// in main split the list 1..6 with chunked(3)
// sum each chunk and printSample solution
fun main() {
val sums = listOf(1, 2, 3, 4, 5, 6).chunked(3) { it.sum() }
println(sums)
}Expected output
[6, 15]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the chunked call
val chunks = listOf(1, 2, 3, 4, 5).____(2)
val chunks = listOf(1, 2, 3, 4, 5).chunked(2)
Explanation: chunked(2) yields pairs of consecutive items.
2 What does listOf(1, 2, 3, 4, 5).chunked(2) return?
- [1, 2, 3, 4, 5]
- [[1, 2], [2, 3], [3, 4], [4, 5]]
- [[1, 2], [3, 4], [5]] Correct answer
- [[1, 2, 3, 4, 5]]
Explanation: chunked yields consecutive chunks; the last may be smaller.
3 Match the chunked parts
| Term | Meaning |
|---|---|
chunked(2) |
Chunk size |
[[1, 2], [3, 4], [5]] |
Result |
chunked { } |
Transform |
last chunk smaller |
Trait |