groupBy 함수
- 컬렉션의 요소들을 특정 조건에 따라 그룹화하여 맵 형태로 결과를 반환
- 각 요소에 대해 제공된 keySelector 함수를 적용하여 반환된 값을 키로 하는 맵을 생성하고, 같은 키를 가진 요소들을 리스트로 묶어 줌
groupBy 함수 사용 예시
각 길이별로 문자열들을 그룹화하고, 각 그룹의 길이와 해당 그룹에 포함된 문자열들을 출력
fun main() {
val words = listOf("a", "abc", "ab", "def", "abcd")
// words.groupBy { it.length } 부분에서 각 문자열의 길이를 기준으로 그룹화
// it.length가 키가 되며, 각 키에 대해 해당 길이의 문자열들로 이루어진 리스트가 맵의 값
words.groupBy { it.length }.map { (length, words) ->
val wordsStr = words.joinToString(", ")
println("Current length is $length. The words: $wordsStr")
}
}
//Current length is 1. The words: a
//Current length is 3. The words: abc, def
//Current length is 2. The words: ab
//Current length is 4. The words: abcd
- 숫자 범위로 그룹화
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
val groupedByRange = numbers.groupBy { it / 3 }
println(groupedByRange)
//{0=[1, 2], 1=[3, 4, 5], 2=[6, 7, 8], 3=[9]}
- 객체의 속성으로 그룹화
data class Person(val name: String, val age: Int)
val people = listOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 30))
val groupedByAge = people.groupBy { it.age }
println(groupedByAge)
//{30=[Person(name=Alice, age=30), Person(name=Charlie, age=30)], 25=[Person(name=Bob, age=25)]}