Let’s say we have a map and want to find a specific key-value pair but it can be located in any order, so to have the map in Golang in a particular order, we can sort the map by its keys or values. In this article, we will see how to sort a map in go lang by its keys or values.

A map is an unordered list of key value pairs. Each key in a map is associated with a value. The value can be removed, modified or retrieved using its key.

In Go a map type is expressed as map[keyType]valueType.

The Golang make function can be used to create maps as i.

Sort By Keys

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

Go: sort by key
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package main

import (
	"fmt"
	"sort"
)

func main() {
	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:

plaintext: output
1
2
3
Alice 23
Bob 25
Eve 2

If key is int, use sort.Ints(sortedIntKeys).

Sort by value

We can even iterate over the map by sorting the values, for that we need to use the sort.SliceStable function.

Firstly, similar to the sorting by key method, we have to obtain a slice of all the keys. Now we want to sort the keys according to the values, for doing that, we use the SliceStable function in the sort module. The slicestable function takes in the slice and we can provide less function. We can simply provide an anonymous/lambda fiction that checks for the comparison of the values of the provided slice. We compare the key at the ith index in the map so it becomes map[slice[i]], here keys is a slice of all the keys in the map and hence we access each key from the map. So, after this, we should have a sorted slice of keys as per the value of those keys.

Go: sort by value
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main

import (
	"fmt"
	"sort"
)

func main() {
	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.SliceStable(keys, func(i, j int) bool {
		return m[keys[i]] < m[keys[j]]
	})

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

OutPut

plaintext: output
1
2
3
Eve 2
Alice 23
Bob 25