Part 10 / Topic 7 of 8
groupBy, associateBy and partition: the group-then-summarize pipeline
groupBy { key } buckets every element into a Map<Key, List<Element>> — nothing is dropped,
and every match for a key survives in that key's list.
val byCity = SHIPMENTS.groupBy { it.city }
val weightByCity = byCity.mapValues { (_, list) -> list.sumOf { it.weightKg } }
groupingBy(...).eachCount() is a dedicated shortcut when only the counts matter — it skips
building the intermediate List<Shipment> per key that a plain groupBy would construct first.
associateBy { key } is different in kind, not just name: it keeps exactly one value per
key (the last match wins on a duplicate key), for fast lookup rather than grouping.
partition { predicate } splits into exactly two lists — (matched, didNotMatch) — in one pass.
val countByCity = SHIPMENTS.groupingBy { it.city }.eachCount()
val byId = SHIPMENTS.associateBy { it.id }
val (delayed, onTime) = SHIPMENTS.partition { it.delayed }
Shipments per city: {Pune=[S-2001, S-2003, S-2005], Mumbai=[S-2002, S-2006], Chennai=[S-2004]}
Total weight by city: {Pune=1905.25, Mumbai=400.0, Chennai=2400.0}
Shipment count by city: {Pune=3, Mumbai=2, Chennai=1}
Lookup S-2004 by id: Chennai
Delayed: [S-2002, S-2004, S-2006], on time: [S-2001, S-2003, S-2005]
Cities with 2+ shipments, heaviest first: [Pune: 1905.25 kg total, Mumbai: 400.00 kg total]
The last line chains the full pipeline: groupBy → filter (keep only cities with 2+
shipments) → mapValues (sum the weight) → sortedByDescending (heaviest city first) → map
(format each line) — group, then summarize, then present, each step a small, named operation.
Full program: examples/07_groupby_pipelines.kt.
Done here? The practice set for Part 10 — including the solutions — is on the part page.