How To Sort Map In Golang

My computer develop environment

1
2
3
4
5
6
7
$ sw_vers 
ProductName: Mac OS X
ProductVersion: 10.12.6
BuildVersion: 16G29

$ go version
go version go1.8.3 darwin/amd64

Introduction Golang map

A Map in Go is a collection of unordered key-value pairs.
The most important point of Map is to quickly retrieve data by key. The key is similar to the index and points to the value of the data.
Maps are a collection, so we can iterate over it like iterating over arrays and slices.
However, Map is unordered, and we can’t determine its return order, because Map is implemented using a chained hash table.

So, when the map is traversed by range, the order of the keys is randomized.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package main

import (
"fmt"
)

func main() {
m := make(map[string]string)
m["error"] = "xxxxxx"
m["code"] = "xxxxxx"
m["message"] = "xxxxxx"
m["is"] = "xxxxxx"
m["list"] = "xxxxxx"

for k, v := range m {
fmt.Printf("k=%v, v=%v\n", k, v)
}
}

It can be clearly seen that the order of the keys is different each time it is traversed.
In Golang office document Go maps in action, you can find the reason.

When iterating over a map with a range loop, the iteration order is not specified and is not guaranteed to be the same from one iteration to the next. Since Go 1 the runtime randomizes map iteration order, as programmers relied on the stable iteration order of the previous implementation.

How to sort a Map?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package sort
import "sort"

type pair struct {
Key string
Val string
}

func SortMap(m map[string]string) (pairs []pair) {
keys := []string{}
for k, _ := range m {
keys = append(keys, k)
}
sort.Strings(keys)

for _, k := range keys {
v := m[k]
if k != "" && v != "" {
pairs = append(pairs, pair{
Key: k,
Val: v,
})
}
}
return pairs
}

Slice is ordered, using this feature, create a slice of the struct type for storage.
These slices will iteratively output the key-value pairs in the Map in order.

Share