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]) } }
func sortMapKey(mp map[string]int) []string { strArray := make([]string, 0) for k, _ := range mp { strArray = append(strArray, k) } sort.Strings(strArray) return strArray }
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 }
|