Go: Sort a map by key or value

  • A map is an unordered collection of key-value pairs.
  • If you need a stable iteration order, you must maintain a separate data structure.

This example uses a sorted slice of keys to print a map[string]int in key order:

m := map[string]int{"Alice": 23, "Eve": 2, "Bob": 25}

keys := make([]string, 0, len(m))
for k := range m {
	keys = append(keys, k)
}
sort.Strings(keys)

for _, k := range keys {
	fmt.Println(k, m[k])
}

Output:

Alice 23
Bob 25
Eve 2

Comments

Be the first to comment!