Library contents

Scala mutable.Map.getOrElseUpdate

Collect parcels under their delivery route as each scan arrives.

A simple example

mutable.Map.getOrElseUpdate

  1. Start with A already holds [1]
  2. Do this Append 2 in the A group
  3. Result A holds [1, 2]
The map locates the group and its list stores both values.

Syntax

Scala syntax
routes.getOrElseUpdate(key, newBucket)
Run these examples in Scala

Save one example at a time as Lesson.scala. Use Scala 2.13 on JDK 21.

scalac Lesson.scala
scala Lesson

Group two parcels on one delivery route

A small courier sorts parcels into a list for each route. The first North parcel needs a new list, while the next North parcel should join that same list without erasing the first one.

ResultP2, P8
Lesson.scala
import scala.collection.mutable

object Lesson {
    def main(args: Array[String]): Unit = {
        val routes = mutable.Map.empty[String, mutable.ArrayBuffer[String]]
        for (parcel <- List("P2", "P8")) {
            routes.getOrElseUpdate("North", mutable.ArrayBuffer.empty[String]) += parcel
        }
        println(routes("North").mkString(", "))
    }
}
Output
P2, P8

Both parcels join the North route in scan order.

Advertisements

Sort returned books onto library carts

At closing time the librarian scans three returned books. Each scan carries a floor number, so books for the same floor belong on one cart even when their scans arrive several minutes apart.

ResultArt, Maps
Lesson.scala
import scala.collection.mutable

object Lesson {
    def main(args: Array[String]): Unit = {
        val carts = mutable.Map.empty[Int, mutable.ArrayBuffer[String]]
        for ((floor, title) <- List((2, "Art"), (1, "Trees"), (2, "Maps"))) {
            carts.getOrElseUpdate(floor, mutable.ArrayBuffer.empty[String]) += title
        }
        println(carts(2).mkString(", "))
    }
}
Output
Art, Maps

The second scan for floor two reuses its cart. Reading that cart returns the titles in the order the librarian scanned them.

Fill the east-studio tote

A courier sorts parcels into destination totes as the labels arrive. Append each parcel to the list for its destination. In what order do the parcels appear in the selected group?

GivenEast P4 · West P8 · East P2
Worked resultP4 · P2

What to watch for

Allocate a fresh buffer for each missing key. A shared bucket would mix different routes.

Documentation for mutable.Map.getOrElseUpdate