본문 바로가기
코틀린/[Extraction] 추출 작업

[Kotlin][Iterable] chunked

by jinwo_o 2024. 8. 29.

이 컬렉션을 각각 주어진 크기를 초과하지 않는 목록의 목록으로 분할합니다.

결과 목록의 마지막 목록에는 지정된 크기보다 적은 수의 요소가 있을 수 있습니다.

public fun <T> Iterable<T>.chunked(size: Int): List<List<T>> {
    return windowed(size, size, partialWindows = true)
}

public fun <R> CharSequence.windowed(size: Int, step: Int = 1, partialWindows: Boolean = false, transform: (CharSequence) -> R): List<R> {
    checkWindowSizeStep(size, step)
    val thisSize = this.length
    val resultCapacity = thisSize / step + if (thisSize % step == 0) 0 else 1
    val result = ArrayList<R>(resultCapacity)
    var index = 0
    while (index in 0 until thisSize) {
        val end = index + size
        val coercedEnd = if (end < 0 || end > thisSize) { if (partialWindows) thisSize else break } else end
        result.add(transform(subSequence(index, coercedEnd)))
        index += step
    }
    return result
}


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]]

 

chunked - Kotlin Programming Language

 

kotlinlang.org

'코틀린 > [Extraction] 추출 작업' 카테고리의 다른 글

[Kotlin][Collection] ifEmpty  (0) 2024.08.30
[Kotlin][String] substring  (0) 2024.08.28
[Kotlin][Collection] unzip  (0) 2024.08.22