The decision
A dispatch summary displays how many orders each depot received. Count records, including repeat destinations, and omit depots with no orders. The summary never displays an order itself.
Read the Kotlin
Count the arrivals at each key
Read groupingBy { it.depot } as a description of how to extract a key from each order. eachCount() traverses the source and increments that key’s counter once for each occurrence. A second scan of an identical box still counts as another order unless the business rule explicitly discards duplicates.
listOf("East", "West", "East").groupingBy { it }.eachCount()
// {East=2, West=1}Choose what stays in memory
With groupBy, a depot’s value is a whole list of orders. Mapping each list to its size returns the right totals, but the lists have already been built. With groupingBy(...).eachCount(), the accumulation retains a counter per observed depot. On a shift with many orders at one depot, the difference is the number of order references retained.
Read an absent count deliberately
No order means no entry for that depot. The bracket lookup returns a nullable Int, so the caller can distinguish missing from an actual count. A tile that displays zero can provide a lookup default. Reading with a default leaves the set of keys alone.
val totals = mapOf("East" to 2)
totals["North"] // null
totals.getOrDefault("North", 0) // 0; keys still contain only EastThe full example
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
class Lesson {
record Order(String depot) {}
static Map<String, Integer> counts(List<Order> orders) {
return orders.stream().collect(Collectors.groupingBy(
Order::depot, Collectors.summingInt(o -> 1)));
}
}data class Order(val depot: String)
fun counts(orders: List<Order>): Map<String, Int> =
orders.groupingBy { it.depot }.eachCount()Inputs and outcomes
| Input | Outcome | Why it matters |
|---|---|---|
N, S, N | N → 2, S → 1 | The second N increments its existing count. |
No orders | Empty map | No synthetic zero-count depot is inserted. |
Walk through the code
- groupBy { it.depot } would build a List<Order> for each key. A count-only report can use groupingBy to describe the key and eachCount to accumulate a number for each depot.
- In Java the downstream collector determines the representation. summingInt receives one for each record. The Java and Kotlin outputs therefore both use integer counters, assuming counts fit in Int.
The Java habit
Replacing groupBy with associateBy keeps one order per depot. Counting entries in that index measures depots, not the orders sent to each one.
When to choose differently
The route planner needs to enumerate individual orders at a depot. A count cannot reconstruct them; groupBy retains the members required for that screen.