Library contents

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

  1. Start with Two entries for A, first 1 then 2
  2. Do this Build an index keyed by A
  3. Result A has 2
The second entry uses the same key and supplies the value that remains in the new map.

Syntax

Kotlin 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.

First output linerevised
Lesson.kt
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)
}
Output
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

Advertisements

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?

GivenA → Ivo · B → Ada · A → Rae
Worked resultRae

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?

GivenG1 → West · G1 → East
Worked resultEast