实现map遍历有序
1. key有序
思路:对key排序,再遍历key输出value
代码如下:既可以从小到大排序,也可以从大到小排序
package main import ( "fmt" "sort" ) func main() { // To create a map as input m := make(map[int]string) m[1] = "a" m[2] = "c" m[0] = "b" // To store the keys in slice in sorted order var keys []int for k := range m { keys = append(keys, k) } sort.Ints(keys) // To perform the opertion you want for _, k := range keys { fmt.Println("Key:", k, "Value:", m[k]) } }
输出结果:
Key: 0 Value: b Key: 1 Value: a Key: 2 Value: c
实例2
package main
import (
"fmt"
"sort"
)
func main() {
// To create a map as input
m := make(map[string]int)
m["tom"] = 2
m["jame"] = 4
m["amy"] = 5
// To store the keys in slice in sorted order
var strs []string
for k := range m {
strs = append(strs, k)
}
sort.Strings(strs)
// To perform the opertion you want
for _, k := range strs {
fmt.Printf("%s %d ", k, m[k])
}
}
输出结果:
amy 5
jame 4
tom 2