The decision
A directory sends profiles in arrival order. A later profile replaces an earlier one with the same ID. Build a lookup that keeps the whole winning profile.
Read the Kotlin
Trace a single key through the input
The braces after associateBy hold a lambda. With one parameter Kotlin lets you call it it. Read { it.id } as “use this user’s ID as the key”. The full user becomes the value. At each new arrival, overwrite that key alone. Looking up the key after the loop returns the user who occupied it last.
val parcels = listOf("A-1", "B-1", "A-2")
val byShelf = parcels.associateBy { parcel -> parcel.first() }
byShelf.getValue('A') // "A-2"; shelf B still holds "B-1"Choose the collision rule when porting toMap
Java’s two-argument Collectors.toMap throws IllegalStateException on a duplicate key, even when both values are equal. The third argument is a merge function. Returning the incoming value gives last-arrival behavior. In Kotlin, adding distinctBy before indexing silently changes that policy because it discards later arrivals before they reach the map.
Keep the history when a lookup will need it
One value per key discards the earlier observations. If the caller needs to examine both ends of a history, groupBy builds a list for each key in input order. Repeated values occupy their own positions. Check the result type when reviewing a port. A Map of single parcels and a Map of parcel lists support different questions.
val history = listOf("A1", "B3", "A2", "A1").groupBy { it.first() }
history.getValue('A') // [A1, A2, A1]The full example
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
class Lesson {
record User(int id, String name) {}
static Map<Integer, User> indexUsers(List<User> users) {
return users.stream().collect(Collectors.toMap(
User::id, Function.identity(),
(previous, incoming) -> incoming
));
}
}data class User(val id: Int, val name: String)
fun indexUsers(users: List<User>): Map<Int, User> =
users.associateBy { it.id }Inputs and outcomes
| Input | Outcome | Why it matters |
|---|---|---|
7 → Ada, 9 → Lin | 7 → Ada, 9 → Lin | Distinct IDs retain both profiles. |
7 → Ada, 9 → Lin, 7 → Noor | 7 → Noor, 9 → Lin | The later occurrence of 7 replaces Ada. ID 9 survives. |
No profiles | Empty map | There is nothing to index. |
Walk through the code
- User::id selects the Java key. Function.identity() keeps the incoming User itself as the value. The merge function runs on a collision and returns its second argument.
- In Kotlin the associateBy lambda selects only the key. The operation already stores each original User as its value. For [Ada #7, Lin #9, Noor #7], the write for Noor replaces Ada at key 7.
- Both versions rely on list order. If the feed arrives out of timestamp order, the last profile might be older. A newest-by-timestamp contract would need an explicit comparison.
The Java habit
Porting Java’s two-argument Collectors.toMap directly to associateBy changes the duplicate case. The Java collector throws IllegalStateException. Kotlin silently retains the final profile for that ID.
When to choose differently
An audit screen needs the history of each ID. Use groupBy { it.id } there: its map values are lists that retain earlier profiles, at the cost of storing the full feed.