Iterate A Map In Sorted Order
Fast recall
Quick revision
Core answer
Practical understanding of Map Iteration And Nil.
Repeating a definition without saying when to use it.
Give one trade-off and say how you would test it.
Interview-ready guide
Interview answer
Since the language forbids relying on iteration order, deterministic iteration is a three-move pattern:
keys := make([]string, 0, len(m)) // pre-sized: no growth
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Println(k, m[k])
}Extract, sort, then walk the keys and index the map. The pre-size on the key slice matters at scale — len(m) is known, so the append loop never reallocates.
Three variations you'll meet:
sort.Strings for string keys, sort.Ints for ints; anything else gets sort.Slice(keys, func(i, j int) bool { ... }) with your comparison.
If you need value-ordered (top-N by count, say), sort the keys with a custom comparator that reads the map: sort.Slice(keys, func(i, j int) bool { return m[keys[i]] > m[keys[j]] }).
If you only need the first N sorted keys, sort a copy or use a partial approach — but profile before adding complexity; full sort of a key slice is fine at most real sizes.
Iterate A Map In Sorted Order
Direct Answer
Collect keys into a slice, sort it, range over the sorted keys — the standard pattern, since map order is deliberately random.
Deep Dive & Architecture
Why doesn't the language just offer a sorted map? Two answers: Go's map is a hash table with no order to expose (unlike a tree map), and the sorted-keys pattern composes with the sort package the language already has — the three-line idiom replaces a data structure.
The pattern's cost profile is worth knowing for performance-sensitive paths: O(n) key extraction, O(n log n) sort, then n map lookups (each O(1)). For iteration that must be deterministic at every scale, that's the honest price; the alternative (maintaining a sorted structure, like an ordered map or a B-tree keyed slice) trades O(log n) inserts for O(1) sorted walks — only worth it when sorted iteration dominates.
The standard library's own precedent: text/template sorts map keys for deterministic output — precisely so that template rendering doesn't change between runs. When your output is a diff, a hash, a golden-file test, or anything compared across executions, deterministic iteration isn't optional — the sorted-keys pattern is the fix. When it's just 'process every entry,' the random order is free and fine.
Common Mistakes & Pitfalls
Repeating a definition without saying when to use it.
Check your understanding
Answer these without looking back at the article.
- What is Map Iteration And Nil, and when would you use it?
- When would you use Map Iteration And Nil in a real project?
- How would you compare Map Iteration And Nil with an alternative?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.