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 |
Tags
- elementAt
- Interface
- ReactNative
- Foreign Key
- animation
- MINUS
- Generic
- ConstraintLayout
- AWS
- union
- map
- 생명주기
- lifecycle
- Kotlin
- Service
- function
- docker
- vuex
- list
- LiveData
- docker-compose
- enum
- class component
- collection
- Swift
- recyclerview
- Filter
- mongoose
- react native
- CLASS
Archives
- Today
- Total
개발 일기
Grouping 본문
kotlin standard library는 collection을 grouping 하는 함수들을 제공을 합니다.
가장 기본적인 것은 groupBy() 함수입니다.
groupBy
기본적으로 람다 함수를 가지고 Map을 Return 합니다.
만약에 람다 함수에서 key가 중복이 되어서 반환을 했을 경우에는 같은 Key에 추가되어서 Map을 Return 합니다.
val numbers = listOf("one", "two", "three", "four", "five")
println(numbers.groupBy { it.first().toUpperCase() })
println(numbers.groupBy(keySelector = { it.first() }, valueTransform = { it.toUpperCase() })
이렇게 표현이 가능합니다.
또 다른 방법으로는 grouping을 사용해서 다음과 같이도 가능합니다.
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.groupingBy { it.first() }.eachCount())
{o=1, t=2, f=2, s=1}
val fruits = listOf("apple", "apricot", "banana", "blueberry", "cherry", "coconut")
// collect only even length Strings
val evenFruits = fruits.groupingBy { it.first() }
.fold(listOf<String>()) { acc, e -> if (e.length % 2 == 0) acc + e else acc }
println(evenFruits) // {a=[], b=[banana], c=[cherry]}
val animals = listOf("raccoon", "reindeer", "cow", "camel", "giraffe", "goat")
// grouping by first char and collect only max of contains vowels
val compareByVowelCount = compareBy { s: String -> s.count { it in "aeiou" } }
val maxVowels = animals.groupingBy { it.first() }.reduce { _, a, b -> maxOf(a, b, compareByVowelCount) }
println(maxVowels) // {r=reindeer, c=camel, g=giraffe}
val numbers = listOf(3, 4, 5, 6, 7, 8, 9)
val aggregated = numbers.groupingBy { it % 3 }.aggregate { key, accumulator: StringBuilder?, element, first ->
if (first) // first element
StringBuilder().append(key).append(":").append(element)
else
accumulator!!.append("-").append(element)
}
println(aggregated.values) // [0:3-6-9, 1:4-7, 2:5-8]
'컴퓨터 언어 > kotlin' 카테고리의 다른 글
List or Set에서 데이터 검색 (0) | 2020.05.29 |
---|---|
Retrieving Collection Parts (0) | 2020.05.28 |
plus and minus Operators (0) | 2020.05.26 |
Filtering (0) | 2020.05.25 |
Collection Transformations (0) | 2020.05.22 |
Comments