Sorted by sort.Slice
If the version of Go is later than 1.7, we can use the sort.Slice
function to quickly sort a map by key or value.
Here is an example:
package main
import (
"fmt"
"sort"
)
func main() {
m1 := map[int]int{
21: 99,
12: 98,
35: 17,
24: 36,
}
type kv struct {
Key int
Value int
}
var s1 []kv
for k, v := range m1 {
s1 = append(s1, kv{k, v})
}
sort.Slice(s1, func(i, j int) bool {
return s1[i].Key < s1[j].Key
})
fmt.Println("Sorted in ascending order by key:")
for _, pair := range s1 {
fmt.Printf("%d, %d\n", pair.Key, pair.Value)
}
}
Run the program:
go run ~/project/map.go
The output is as follows:
Sorted in ascending order by key:
12, 98
21, 99
24, 36
35, 17
In this program, we used a struct to store the key-value pairs from the map. We then sorted the slice of structs using the sort.Slice()
function and an anonymous comparison function.
We can also use sort.Slice
to sort the map in descending order by key or in ascending order by value.