Library contents

Kotlin MutableMap.getOrPut

Register the first customer for a seat without replacing an existing reservation.

A simple example

MutableMap.getOrPut

  1. Start with A = 1
  2. Do this Insert A = 2 only if absent
  3. Result A stays 1
The key already exists, so the original value is kept.

Syntax

Kotlin syntax
seats.getOrPut(key) { firstName }
Run these examples in Kotlin

Save one example at a time as Lesson.kt. Use Kotlin 2.2 on JDK 21.

kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar

Keep the first reservation for a seat

Two students ask for the same seat at a school play. The desk enters the requests in order and needs the first confirmed student's name to survive the second request.

ResultMira
Lesson.kt
fun main() {
    val seats = mutableMapOf<String, String>()
    for (student in listOf("Mira", "Sam")) {
        seats.getOrPut("A1") { student }
    }
    println(seats.getValue("A1"))
}
Output
Mira

Mira arrives before Sam and keeps the reservation for A1.

Advertisements

Reserve the kiln

Two potters ask to use the same afternoon slot. Two people claim the same slot in order. Keep the first recorded name and read it after both requests.

GivenFirst Lin · next Bo
Worked resultLin

Assign a library carrel

Two students request the only window desk. Two people claim the same slot in order. Keep the first recorded name and read it after both requests.

GivenFirst Dev · next Uma
Worked resultDev

What to watch for

A null stored value also triggers the default lambda. For concurrency, choose a suitable synchronized design.

Documentation for MutableMap.getOrPut