본문 바로가기
코틀린/[Aggregation] 집계 작업

[Kotlin][Collection] reduce / reduceIndexed

by jinwo_o 2024. 8. 12.

첫 번째 요소부터 시작하여 현재 누산기 값과 각 요소에 왼쪽에서 오른쪽으로 연산을 적용하여 값을 누적합니다. 이 배열이 비어 있으면 예외가 발생합니다. 배열이 예상대로 비워질 수 있는 경우 대신 ReduceOrNull 을 사용하세요. 수신자가 비어 있으면 null 을 반환합니다.

public inline fun <S, T : S> Iterable<T>.reduce(operation: (acc: S, T) -> S): S {
    val iterator = this.iterator()
    if (!iterator.hasNext()) throw UnsupportedOperationException("Empty collection can't be reduced.")
    var accumulator: S = iterator.next()
    while (iterator.hasNext()) {
        accumulator = operation(accumulator, iterator.next())
    }
    return accumulator
}


val strings = listOf("a", "b", "c", "d")
println(strings.reduce { acc, string -> acc + string }) // abcd

// emptyList<Int>().reduce { _, _ -> 0 } //  will fail

 

첫 번째 요소부터 시작하여 왼쪽에서 오른쪽으로 현재 누산기 값과 원본 컬렉션의 인덱스가 있는 각 요소에 연산을 적용하여 값을 누적합니다. 이 컬렉션이 비어 있으면 예외가 발생합니다. 컬렉션이 예상대로 비어 있을 수 있는 경우 대신 ReduceIndexedOrNull 을 사용하세요. 수신자가 비어 있으면 null 을 반환합니다.

public inline fun <S, T : S> Iterable<T>.reduceIndexed(operation: (index: Int, acc: S, T) -> S): S {
    val iterator = this.iterator()
    if (!iterator.hasNext()) throw UnsupportedOperationException("Empty collection can't be reduced.")
    var index = 1
    var accumulator: S = iterator.next()
    while (iterator.hasNext()) {
        accumulator = operation(checkIndexOverflow(index++), accumulator, iterator.next())
    }
    return accumulator
}


val strings = listOf("a", "b", "c", "d")
println(strings.reduceIndexed { index, acc, string -> acc + string + index }) // ab1c2d3

 

reduce - Kotlin Programming Language

 

kotlinlang.org

 

reduceIndexed - Kotlin Programming Language

 

kotlinlang.org