코틀린 언어 정리 4-10
Collection operations
Common operations( 일반적인 연산들 )
Aggregation Operations
코틀린에서 일반적으로 잘 알려진 집계 연산들을 제공합니다. 컬렉션의 모든 요소들의 개수, 합계, 최소/최대값 등을 구하는 함수, 그 외 모든 요소들을 적용하여 임의의 연산을 수행할 수 있는 일반화된 fold, reduce등을 제공합니다.
숫자 계산 집계 함수들
Number Type 전용 집계 함수들
min/max
average/sum/count
selector나 comparator를 적용할 수 있는 함수들
maxBy/minBy, sumBy/sumByDouble
maxWith/minWith
일반화된 집계 함수들
fold and reduce
이전까지 모든 요소들의 누적 연산 결과와 현재 요소를 입력 받아 결과를 만들고 이 결과는 다시 다음 요소의 계산에 누적 연산 결과 값으로 전달합니다. fold, reduce 외에 더 일반화된 aggregate 함수도 있으나 이 함수는 Array / List 등에서는 지원하지 않고, groupingBy에 의해 리턴되는 Grouping<T, K> 클래스에서 지원합니다.
유사 함수들
fold, foldIndexed, foldRight, foldRightIndexed, reduce, reduceIndexed, reduceRightIndexed
주요 함수 형식
Receiver Type에 따라 각각 정의가 있으며 그 중 하나를 보면 다음과 같습니다.
inline fun <T, R> Array<out T>.fold ( initial: R, operation: { acc: R, ele: T }->R ): R
inline fun <S, T: S> Array<out T>.reduce ( operation: ( acc: S, ele: T )->S ): S
전체 예제
groupingBy를 이용한 reduce, fold, aggregate 예제
'코틀린( Kotlin )' 카테고리의 다른 글
코틀린 5-1 Reflection - Class References & Bound Class References (0) | 2020.04.14 |
---|---|
코틀린 4-11 Collection operations - Write operations (0) | 2020.04.14 |
코틀린 4-9 Collection operations - Collection Ordering( 컬렉션 정렬 ) (0) | 2020.04.13 |
코틀린 4-8 Collection operations - Retrieving Single Elements( 단일 요소 검색 ) (0) | 2020.04.13 |
코틀린 4-7 Collection operations - Retrieving Collection Parts (0) | 2020.04.13 |