Kotlin
groupBy and partition
Learn grouping with groupBy and partition.
groupBy and partition
groupBy groups elements by a key and returns Map<K, List<V>>. Example: people.groupBy { it.city } groups by city; each city becomes a key. Elements with the same key land in the same list.
partition splits the list by a condition into a Pair: the first list holds matching elements, the second holds the rest. Example: val (adults, kids) = people.partition { it.age >= 18 }. This is a short way to split into two groups with one condition.
groupBy and partition examples
In the result of groupBy each key maps to a list. After people.groupBy { it.city }, result["London"] gives the people in London. The number of keys equals the number of distinct cities.
The result of partition is unpacked with destructuring: val (yes, no) = list.partition { ... }. The first variable gets matching elements, the second gets the rest. This is more efficient than calling filter twice because the list is split in a single pass.
Exercise Apply groupBy and partition
Define data class Person(val name: String, val city: String, val age: Int). Create listOf(Person("Alex", "London", 30), Person("Sam", "Paris", 15)). Group by city with groupBy { it.city } and print println("Cities: ${byCity.keys}"). Split by age with partition { it.age >= 18 } and print println("Adults: ${adults.size}").
Show example solution
data class Person(val name: String, val city: String, val age: Int)
fun main() {
val people = listOf(Person("Alex", "London", 30), Person("Sam", "Paris", 15))
val byCity = people.groupBy { it.city }
val (adults, kids) = people.partition { it.age >= 18 }
println("Cities: ${byCity.keys}")
println("Adults: ${adults.size}")
}
Test yourself
-
Match groupBy and partition
- groupBy
- Group by key
- partition
- Split in two
- Pair
- Two lists
- Map<K, List<V>>
- Group result
-
What does partition return?
- A single list
- A Pair of two lists
- A Map
- A Set
Show answer
A Pair of two lists — partition returns a Pair of matching and non-matching lists.
-
Complete the groupBy call
people.____ { it.city }
Show answer
people.groupBy { it.city }
Next lesson: sortedBy and sortedWith