0
0
KotlinHow-ToBeginner · 3 min read

How to Chunk List in Kotlin: Simple Guide with Examples

In Kotlin, you can split a list into smaller parts using the chunked() function. It takes the size of each chunk as a parameter and returns a list of lists, each containing that many elements (except possibly the last chunk).
📐

Syntax

The chunked() function is called on a list and takes one required parameter: the size of each chunk. It returns a new list containing sublists (chunks) of the specified size.

  • chunked(size: Int): Splits the list into chunks of size.
kotlin
val chunks = list.chunked(size)
💻

Example

This example shows how to split a list of numbers into chunks of size 3 using chunked(). It prints each chunk on a new line.

kotlin
fun main() {
    val numbers = listOf(1, 2, 3, 4, 5, 6, 7)
    val chunks = numbers.chunked(3)
    for (chunk in chunks) {
        println(chunk)
    }
}
Output
[1, 2, 3] [4, 5, 6] [7]
⚠️

Common Pitfalls

One common mistake is expecting chunked() to modify the original list. It does not; it returns a new list of chunks. Another is using a chunk size larger than the list, which simply returns one chunk with all elements.

Also, passing zero or negative numbers as chunk size will cause an IllegalArgumentException.

kotlin
fun main() {
    val list = listOf(1, 2, 3)
    // Wrong: chunk size zero causes error
    // val chunks = list.chunked(0) // Throws IllegalArgumentException

    // Correct usage:
    val chunks = list.chunked(5)
    println(chunks) // Output: [[1, 2, 3]]
}
Output
[[1, 2, 3]]
📊

Quick Reference

  • chunked(size): Splits list into chunks of given size.
  • Returns a list of lists.
  • Last chunk may be smaller if elements don't divide evenly.
  • Throws error if size <= 0.

Key Takeaways

Use chunked(size) to split a list into smaller lists of fixed size.
The function returns a new list; it does not change the original list.
The last chunk may have fewer elements if the list size isn't divisible by chunk size.
Passing zero or negative chunk size causes an error.
If chunk size is larger than the list, the result is a single chunk with all elements.