CodeBlanks Logo Icon CodeBlanks

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.

Practice 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}").

Starter code

Main.kt
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))
    // Group by city with groupBy, split by age with partition, and print
}

Sample solution

Main.kt
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}")
}

Expected output

Cities: [London, Paris]
Adults: 1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match groupBy and partition

Term Meaning
groupBy Group by key
partition Split in two
Pair Two lists
Map<K, List<V>> Group result

2 What does partition return?

  • A single list
  • A Pair of two lists Correct answer
  • A Map
  • A Set

Explanation: partition returns a Pair of matching and non-matching lists.

3 Complete the groupBy call

Question
people.____ { it.city }
Answer
people.groupBy { it.city }

Explanation: answer: groupBy. groupBy produces a Map by key.

All lessons in Intermediate