How to iterate over a Golang map in sorted order

As a Golang map is an unordered collection, it does not preserve the order of keys. We can use additional data structures to iterate over these maps in sorted order.

Code

Let’s say we have a map of the first and last names of language designers. We want to print first and last names in sorted order by their first name.

We need to perform the following:

  1. Create a slice.
  2. Store keys to the slice.
  3. Sort the slice by keys.
  4. Iterate over the map by the sorted slice.
package main
import (
"fmt"
"sort"
)
func main() {
designedBy := map[string]string {
"Robert": "Griesemer",
"Rob" : "Pike",
"Ken": "Thompson",
}
// create slice and store keys
firstNames := make([]string, 0, len(designedBy))
for k := range designedBy {
firstNames = append(firstNames, k)
}
// sort the slice by keys
sort.Strings(firstNames)
// iterate by sorted keys
for i, firstName := range firstNames {
fmt.Println(i+1, firstName, designedBy[firstName])
}
}

In Go version 1.12https://go.dev/doc/go1.12 and later, maps are printed in key-sorted order to ease testing.

Free Resources