W3cubDocs

/Kotlin

chunked

Platform and version requirements: JVM (1.2), JS (1.2), Native (1.2)
fun <T> Sequence<T>.chunked(size: Int): Sequence<List<T>>

Splits this sequence into a sequence of lists each not exceeding the given size.

The last list in the resulting sequence may have less elements than the given size.

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val words = "one two three four five six seven eight nine ten".split(' ')
val chunks = words.chunked(3)

println(chunks) // [[one, two, three], [four, five, six], [seven, eight, nine], [ten]]
//sampleEnd
}

Parameters

size -

the number of elements to take in each list, must be positive and can be greater than the number of elements in this sequence.

The operation is intermediate and stateful.

Platform and version requirements: JVM (1.2), JS (1.2), Native (1.2)
fun <T, R> Sequence<T>.chunked(
    size: Int, 
    transform: (List<T>) -> R
): Sequence<R>

Splits this sequence into several lists each not exceeding the given size and applies the given transform function to an each.

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val codonTable = mapOf("ATT" to "Isoleucine", "CAA" to "Glutamine", "CGC" to "Arginine", "GGC" to "Glycine")
val dnaFragment = "ATTCGCGGCCGCCAA"

val proteins = dnaFragment.chunked(3) { codon: CharSequence -> codonTable[codon.toString()] ?: error("Unknown codon") }

println(proteins) // [Isoleucine, Arginine, Glycine, Arginine, Glutamine]
//sampleEnd
}

Parameters

size -

the number of elements to take in each list, must be positive and can be greater than the number of elements in this sequence.

The operation is intermediate and stateful.

Return

sequence of results of the transform applied to an each list.

Note that the list passed to the transform function is ephemeral and is valid only inside that function. You should not store it or allow it to escape in some way, unless you made a snapshot of it. The last list may have less elements than the given size.

© 2010–2020 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/chunked.html