List — groupBy() / partition()
In Kotlin, groupBy() groups a list by a key selector and returns the result as a Map. partition() splits a list into two parts based on a condition. Use these functions to classify or distribute data.
Syntax
val numbers = listOf(1, 2, 3, 4, 5, 6)
// groupBy — Groups elements by a key.
val grouped = numbers.groupBy { if (it % 2 == 0) "even" else "odd" }
// {"odd": [1, 3, 5], "even": [2, 4, 6]}
// partition — Splits into two lists based on a condition.
val (evens, odds) = numbers.partition { it % 2 == 0 }
// evens: [2, 4, 6], odds: [1, 3, 5]
Method List
| Method | Description |
|---|---|
| list.groupBy { key } | Returns a Map<K, List<T>> with elements grouped by the key selector. |
| list.groupBy({ key }, { valueTransform }) | Groups elements by key with an additional value transformation. |
| list.groupingBy { key }.eachCount() | Returns a Map<K, Int> with the count of elements per group. |
| list.partition { condition } | Returns a Pair<List, List> of elements that match and do not match the condition. |
| list.chunked(n) | Splits the list into sublists of up to n elements each. |
| list.windowed(n) | Generates sublists using a sliding window of size n. |
Sample Code
data class Student(val name: String, val grade: String, val score: Int)
fun main() {
val students = listOf(
Student("Alice", "A", 95),
Student("Bob", "B", 75),
Student("Carol", "A", 88),
Student("Dave", "C", 62),
Student("Eve", "B", 80),
Student("Frank", "C", 58)
)
// groupBy — Groups students by grade.
val byGrade = students.groupBy { it.grade }
println("=== By Grade ===")
byGrade.forEach { (grade, list) ->
val names = list.map { it.name }
println("$grade: $names")
}
// groupBy with value transformation (group names only)
val namesByGrade = students.groupBy({ it.grade }, { it.name })
println("\nGrade -> Names: $namesByGrade")
// Count per group
val countByGrade = students.groupingBy { it.grade }.eachCount()
println("Count: $countByGrade")
println()
// partition — Splits into passing (70+) and failing students.
val (passed, failed) = students.partition { it.score >= 70 }
println("=== Pass / Fail ===")
println("Passed: ${passed.map { it.name }}")
println("Failed: ${failed.map { it.name }}")
println()
// chunked — Useful for batch processing (3 at a time)
val chunks = students.chunked(3)
println("=== Batch Processing ===")
chunks.forEachIndexed { i, batch ->
println("Batch $i: ${batch.map { it.name }}")
}
println()
// windowed — Useful for moving averages (sliding window of 3)
val scores = students.map { it.score }
val windows = scores.windowed(3)
println("=== 3-Point Moving Average ===")
windows.forEach { w ->
println("$w -> Average: ${"%.1f".format(w.average())}")
}
}
Notes
groupBy() is the Kotlin equivalent of SQL's GROUP BY. The return type is Map<K, List<T>>, so you can further aggregate each group (e.g., map { it.value.size }).
partition() is a simple operation for splitting into two groups. Using destructuring declarations (val (a, b) = ...) keeps the code concise. To split into three or more groups, use groupBy() instead.
For folding and aggregation, see List — reduce() / fold(). For flattening, see List — flatMap() / flatten().
If you find any errors or copyright issues, please contact us.