Library contents

Go Range over sorted map keys

Visit both the label and count of each shelf and print them in aisle order.

A simple example

Range over sorted map keys

  1. Start with B = 2, A = 1
  2. Do this Visit entries in key order
  3. Result A = 1, then B = 2
Ordering the keys before visiting them gives a predictable sequence.

Syntax

Go syntax
for _, key := range keys
Run these examples in Go

Save one example at a time as main.go. Use Go 1.21 or later.

go run main.go

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

ResultA=4, B=2
main.go
package main

import (
    "fmt"
    "slices"
    "strings"
)

func main() {
    stock := map[string]int{"B": 2, "A": 4}
    var keys, lines []string
    for aisle := range stock {
        keys = append(keys, aisle)
    }
    slices.Sort(keys)
    for _, aisle := range keys {
        lines = append(lines, fmt.Sprintf("%s=%d", aisle, stock[aisle]))
    }
    fmt.Println(strings.Join(lines, ", "))
}
Output
A=4, B=2

The report prints A with its four items before B with its two.

Advertisements

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?

GivenB → 3 · A → 2
Worked resultA 2 · B 3

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?

GivenWest → 8 · East → 4
Worked resultEast 4 · West 8

What to watch for

Go map iteration order is unspecified. Sort the keys when the printed order is part of the report.

Documentation for Range over sorted map keys