Go语言-Map排序

缘由

由于map输出是无序的,我希望map输出有序

代码

package main

import (
"fmt"
"sort"
)

func main() {
mp := make(map[string]int)
mp["1"] = 1
mp["5"] = 45
mp["6"] = 3
mp["4"] = 22
mp["2"] = 5
mp["3"] = 16

fmt.Println("---------------正序----------------")
for _, v := range sortMapKey(mp) {
fmt.Println("key:", v, " value:", mp[v])
}

fmt.Println("---------------倒序----------------")

for _, v := range reverseMapKey(mp) {
fmt.Println("key:", v, " value:", mp[v])
}
}

// map 根据 key 正序排序
func sortMapKey(mp map[string]int) []string {
strArray := make([]string, 0)
for k, _ := range mp {
strArray = append(strArray, k)
}
sort.Strings(strArray)
return strArray
}

// map 根据 key 倒序排序
func reverseMapKey(mp map[string]int) []string {
strArray := make([]string, 0)
for k, _ := range mp {
strArray = append(strArray, k)
}
sort.Sort(sort.Reverse(sort.StringSlice(strArray)))
return strArray
}

结果

---------------正序----------------
key: 1 value: 1
key: 2 value: 5
key: 3 value: 16
key: 4 value: 22
key: 5 value: 45
key: 6 value: 3
---------------倒序----------------
key: 6 value: 3
key: 5 value: 45
key: 4 value: 22
key: 3 value: 16
key: 2 value: 5
key: 1 value: 1