go语言之map排序
package main
import (
"sort"
"fmt"
)
func main() {
lockTest()
}
func lockTest() {
var mp map[string]int
mp = make(map[string]int)
mp["1"] = 1
mp["5"] = 45
mp["6"] = 3
mp["4"] = 22
mp["2"] = 5
mp["3"] = 16
sortMap(mp)
fmt.Println()
sortMap2(mp)
}
/**
根据key排序
*/
func sortMap2(mp map[string]int) {
var newMp = make([]string, 0)
for k, _ := range mp {
newMp = append(newMp, k)
}
sort.Strings(newMp)
for _, v := range newMp {
fmt.Println("根据key排序后的新集合》》 key:", v, " value:", mp[v])
}
}
/**
根据value排序
*/
func sortMap(mp map[string]int) {
var newMp = make([]int, 0)
var newMpKey = make([]string, 0)
for oldk, v := range mp {
newMp = append(newMp, v)
newMpKey = append(newMpKey, oldk)
}
sort.Ints(newMp)
for k, v := range newMp {
fmt.Println("根据value排序后的新集合》》 key:", newMpKey[k], " value:", v)
}
}
如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!
txttool.com 说一段 esp56物联 查询128 IP查询