Hanbit the Developer

Kotlin Documentation | Group elements 본문

Mobile/Kotlin

Kotlin Documentation | Group elements

hanbikan 2023. 5. 24. 14:17

Kotlin Documentation 시리즈에 대해

Category: Standard library - Collections

문서 링크: https://kotlinlang.org/docs/collection-grouping.html


groupBy()는 람다 함수를 통해 key를 만들어 Map을 반환한다.

val numbers = listOf("one", "two", "three", "four", "five")
println(numbers.groupBy { it.first().uppercase() })
println(numbers.groupBy(keySelector = { it.first() }, valueTransform = { it.uppercase() }))
{O=[one], T=[two, three], F=[four, five]}
{o=[ONE], t=[TWO, THREE], f=[FOUR, FIVE]}

groupingBy()를 통해 Grouping 타입 인스턴스를 반환받고 모든 그룹에 대해 명령을 한번에 수행할 수 있다.

Grouping은 다음 명령들을 지원한다:

  • eachCount()
  • fold(), reduce()
  • aggregate(): 연산을 순차적으로 적용한다.
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.groupingBy { it.first() }.eachCount())
{o=1, t=2, f=2, s=1}