Kotlin associateBy
associateBy builds a map keyed by a selector. When several records produce the same key, the last record supplies the stored value.
A simple example
associateBy
- Start with Two entries for A, first 1 then 2
- Do this Build an index keyed by A
- Result A has 2
Syntax
val byId = rows.associateBy { it.id }
Run this example in Kotlin
Save the program as Lesson.kt. Use Kotlin 2.2 on the JVM.
kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar
Index records by a possibly repeated identifier
An export contains keys that may identify more than one input record. Establish what happens at a repeated key before constructing the lookup so useful records are not discarded unintentionally.
data class Entry(val id: Int, val label: String)
fun main() {
val rows = listOf(Entry(7, "draft"), Entry(8, "ready"), Entry(7, "revised"))
val latest = rows.associateBy { it.id }
println(latest.getValue(7).label)
println(rows.groupBy { it.id }.getValue(7).size)
}
revised 2
With repeated identifiers, associateBy gives a latest-record lookup in input order. Use groupBy when a reader needs to preserve the full history of each identifier.
Kotlin documentation for associateBy
Replace a room’s contact
A caretaker imports an older duty roster followed by the current roster. Build the lookup in the supplied order. A later record with the same key replaces the earlier value. Which value is returned for that key?
Update an exhibit assignment
A gallery reassigns its only audio guide during the morning. Build the lookup in the supplied order. A later record with the same key replaces the earlier value. Which value is returned for that key?