Scala mutable.Map.getOrElseUpdate
Collect parcels under their delivery route as each scan arrives.
A simple example
mutable.Map.getOrElseUpdate
- Start with A already holds [1]
- Do this Append 2 in the A group
- Result A holds [1, 2]
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 LessonGroup 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.
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(", "))
}
}
P2, P8
Both parcels join the North route in scan order.
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.
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(", "))
}
}
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?
What to watch for
Allocate a fresh buffer for each missing key. A shared bucket would mix different routes.