Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- enum
- Kotlin
- elementAt
- Generic
- lifecycle
- Swift
- ConstraintLayout
- docker-compose
- mongoose
- 생명주기
- collection
- LiveData
- MINUS
- docker
- vuex
- react native
- Interface
- class component
- map
- animation
- function
- CLASS
- AWS
- union
- Service
- recyclerview
- Filter
- list
- ReactNative
- Foreign Key
Archives
- Today
- Total
개발 일기
Collection Aggregate Operations 본문
기존에 다른 언어에서도 잘 알려진 Aggregate Operations 함수를 코틀린에서도 제공하고 있습니다
min , max
min은 집합 중에서 제일 작은값 , max는 집합 중에서 가장 큰 값 입니다.
average
집합 중에서 평균 값을 정할수가 있습니다.
sum
집합에 있는 내용을 전부 더한 값을 알수가 있습니다.
count
집합에 있는 개수를 알수가 있습니다.
val numbers = listOf(6, 42, 10, 4)
println("Count: ${numbers.count()}")
println("Max: ${numbers.max()}")
println("Min: ${numbers.min()}")
println("Average: ${numbers.average()}")
println("Sum: ${numbers.sum()}")
Count: 4
Max: 42
Min: 4
Average: 15.5
Sum: 62
가장 작은값 혹은 가장 큰값을 selector function or Custom Comparator로 찾을수가 있습니다.
selector function - maxBy or minBy
comparator - maxWith or minWith
val numbers = listOf(5, 42, 10, 4)
val min3Remainder = numbers.minBy { it % 3 }
println(min3Remainder)
val strings = listOf("one", "two", "three", "four")
val longestString = strings.maxWith(compareBy { it.length })
println(longestString)
sumBy , sumByDouble
함수를 포함하고 함수의 결과값에 대해서 Return 합니다.
val numbers = listOf(1,2,3)
println(numbers.sumBy { it * 2 })
println(numbers.sumByDouble { it.toDouble() / 2 })
12
3.0
Fold and reduce
Fold 와 reduce는 연산값을 축적 시켜서 해당 값을 Return 합니다.
둘에 대해서 차이점은 초기화 값에 대해서 존재여부입니다.
val numbers = listOf(5, 2, 10, 4)
val sum = numbers.reduce { sum, element -> sum + element }
println(sum)
val sumDoubled = numbers.fold(1) { sum, element ->
sum + element}
println(sumDoubled)
21
22
만약에 앞에서 부터 순서가 시작되는게 아니라 뒤에서부터 시작되고 싶은 경우에는 reduceRight() and foldRight()을 사용할수가 있습니다.
val numbers = listOf(5, 2, 10, 4)
val sumDoubledRight = numbers.foldRight(0) { element, sum -> sum + element * 2 }
println(sumDoubledRight)
마지막으로 해당 값에 Index가 필요할 경우에는 다음과 같이 사용이 가능합니다.
reduceIndexed() and foldIndexed()
reduceRightIndexed() and foldRightIndexed().
val numbers = listOf(5, 2, 10, 4)
val sumEven = numbers.foldIndexed(0) { idx, sum, element -> if (idx % 2 == 0) sum + element else sum }
println(sumEven)
val sumEvenRight = numbers.foldRightIndexed(0) { idx, element, sum -> if (idx % 2 == 0) sum + element else sum }
println(sumEvenRight)
'컴퓨터 언어 > kotlin' 카테고리의 다른 글
List Specific Operations (0) | 2020.06.05 |
---|---|
Collection Write Operations (0) | 2020.06.03 |
Collection 순서 정렬 (0) | 2020.06.01 |
List or Set에서 데이터 검색 (0) | 2020.05.29 |
Retrieving Collection Parts (0) | 2020.05.28 |
Comments