Kotlin List.chunked()
The List.chunked() function in Kotlin is used to split a list into chunks of a specified size, creating a list of lists.
Syntax
fun <T> Iterable<T>.chunked(size: Int, transform: (List<T>) -> R): List<R>
The function takes a size
parameter, representing the size of each chunk, and an optional transform
function that can be applied to each chunk.
Parameter | Description |
---|---|
size | The size of each chunk. |
transform | Optional. A function that can be applied to each chunk. |
T
is the type of elements in the list.
Example 1: Basic Chunking using List.chunked()
Split a list of numbers into chunks of size 3.
Kotlin Program
fun main() {
val numbers = (1..10).toList()
val chunkedNumbers = numbers.chunked(3)
println(chunkedNumbers)
}
Output
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
This example uses the chunked
function to split a list of numbers into chunks of size 3.
Example 2: Applying Transform using List.chunked()
Split a list of names into chunks of size 2 and convert each chunk to uppercase.
Kotlin Program
fun main() {
val names = listOf("Alice", "Bob", "Charlie", "David", "Eva", "Frank")
val chunkedNames = names.chunked(2) { it.map(String::toUpperCase) }
println(chunkedNames)
}
Output
[[ALICE, BOB], [CHARLIE, DAVID], [EVA, FRANK]]
This example uses the chunked
function with a transform to split a list of names into chunks of size 2 and convert each name to uppercase.
Summary
In this tutorial, we learned about Kotlin List.chunked() function with syntax and examples.