Kotlin List chunked()
Syntax & Examples
Syntax of List.chunked()
There are 2 variations for the syntax of List.chunked() extension function. They are:
1.
fun <T> Iterable<T>.chunked(size: Int): List<List<T>>This extension function splits this collection into a list of lists each not exceeding the given size.
2.
fun <T, R> Iterable<T>.chunked( size: Int, transform: (List<T>) -> R ): List<R>This extension function splits this collection into several lists each not exceeding the given size and applies the given transform function to an each.
✐ Examples
1 Example
In this example,
- We create a list named
listcontaining integers from 1 to 8. - We use the
chunkedfunction to splitlistinto sublists of size 3. - The resulting chunked list is stored in
chunkedList. - We print the chunked list using
println.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5, 6, 7, 8)
val chunkedList = list.chunked(3)
println(chunkedList)
}Output
[[1, 2, 3], [4, 5, 6], [7, 8]]
2 Example
In this example,
- We create a list named
listcontaining characters'a', 'b', 'c', 'd', 'e', 'f'. - We use the
chunkedfunction to splitlistinto sublists of size 2. - The resulting chunked list is stored in
chunkedList. - We print the chunked list using
println.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf('a', 'b', 'c', 'd', 'e', 'f')
val chunkedList = list.chunked(2)
println(chunkedList)
}Output
[[a, b], [c, d], [e, f]]
3 Example
In this example,
- We create a list named
listcontaining strings"apple", "banana", "cherry", "grape", "orange", "pear". - We use the
chunkedfunction to splitlistinto sublists of size 2. - The resulting chunked list is stored in
chunkedList. - We print the chunked list using
println.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry", "grape", "orange", "pear")
val chunkedList = list.chunked(2)
println(chunkedList)
}Output
[apple, banana], [cherry, grape], [orange, pear]
Summary
In this Kotlin tutorial, we learned about chunked() extension function of List: the syntax and few working examples with output and detailed explanation for each example.