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:
- Create a slice.
- Store keys to the slice.
- Sort the slice by keys.
- Iterate over the map by the sorted slice.
package mainimport ("fmt""sort")func main() {designedBy := map[string]string {"Robert": "Griesemer","Rob" : "Pike","Ken": "Thompson",}// create slice and store keysfirstNames := make([]string, 0, len(designedBy))for k := range designedBy {firstNames = append(firstNames, k)}// sort the slice by keyssort.Strings(firstNames)// iterate by sorted keysfor i, firstName := range firstNames {fmt.Println(i+1, firstName, designedBy[firstName])}}
In Go
and later, maps are printed in key-sorted order to ease testing. version 1.12 https://go.dev/doc/go1.12