forked from kimriri/kotlin_study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Group.kt
43 lines (37 loc) · 1.25 KB
/
Group.kt
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
32
33
34
35
36
37
38
39
40
41
42
43
// ref : https://kotlinlang.org/docs/collection-grouping.html
fun main() {
}
fun groupBySampleCode() {
val numbers = listOf("one", "two", "three", "four", "five")
println(numbers.groupBy { it.first().toUpperCase() })
println(numbers.groupBy(keySelector = { it.first() }, valueTransform = { it.toUpperCase() }))
}
fun groupingBySampleCode() {
val numbers = listOf("one", "two", "three", "four", "five", "six", "fffive")
val groupingResult = numbers.groupingBy { it.first() }
println(groupingResult.eachCount())
println(groupingResult.fold("one") { a, b ->
println("----")
println(a)
println(b)
println("----")
a + b })
println("@@@")
println(groupingResult.reduce { a, b, c ->
println("----")
println(a)
println(b)
println(c)
println("----")
a + b + c
})
val numberAggregated = listOf(3, 4, 5, 6, 7, 8, 9)
val aggregated = numberAggregated.groupingBy { it % 3 }.aggregate { key, accumulator: StringBuilder?, element, first ->
if (first)
StringBuilder().append(key).append(":").append(element)
else
accumulator!!.append("-").append(element)
}
println(aggregated)
println(aggregated.values)
}