Kotlin Map.entries and toSortedMap
Visit both the label and count of each shelf and print them in aisle order.
A simple example
Map.entries and toSortedMap
- Start with B = 2, A = 1
- Do this Visit entries in key order
- Result A = 1, then B = 2
Syntax
stock.toSortedMap().entries
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.jarPrint shelf totals in aisle order
A stockroom supervisor sends a short inventory message each evening. Both the aisle name and its count belong on each line, and the message must follow aisle order every time.
fun main() {
val stock = mapOf("B" to 2, "A" to 4)
println(stock.toSortedMap().entries.joinToString(", ") { (key, value) -> "$key=$value" })
}
A=4, B=2
The report prints A with its four items before B with its two.
Print stock by aisle
A delivery entered the second aisle before the first. The clerk sorts the keys before printing each key beside its associated value. What appears on the labels?
Print counts by room
A teacher recorded West before East during the count. The clerk sorts the keys before printing each key beside its associated value. What appears on the labels?
What to watch for
Sort string keys for aisle order. Insertion order can differ from the order required for a report.