golang之map排序

map按key顺序获取value

package main

import (
    "fmt"
    "sort"
)

func main() {
    m := make(map[string]int, 5)
    fmt.Printf("%T[%p](%d): %v\n", m, &m, len(m), m)
    m["wang"] = 1
    m["wangq"] = 2
    m["wangh"] = 3
    m["hua"] = 4
    m["huaq"] = 5
    fmt.Printf("%T[%p](%d): %v\n", m, &m, len(m), m)
    m["huaw"] = 6
    m["qing"] = 7
    m["qingw"] = 8
    fmt.Printf("%T[%p](%d): %v\n", m, &m, len(m), m)

    mlen := len(m)
    ss := make([]string, 0, mlen)
    for k := range m {
        ss = append(ss, k)
    }
    sort.Strings(ss)
    sort.Sort(sort.Reverse(sort.StringSlice(ss)))
    fmt.Println(ss)
    for _, v := range ss {
        fmt.Printf("%s:%d ", v, m[v])
    }
}
//////
map[string]int[0xc000136018](0): map[]
map[string]int[0xc000136018](5): map[hua:4 huaq:5 wang:1 wangh:3 wangq:2]
map[string]int[0xc000136018](8): map[hua:4 huaq:5 huaw:6 qing:7 qingw:8 wang:1 wangh:3 wangq:2]
[wangq wangh wang qingw qing huaw huaq hua]
wangq:2 wangh:3 wang:1 qingw:8 qing:7 huaw:6 huaq:5 hua:4 

注:map() make时大小无关,An empty map is allocated with enough space to hold the specified number of elements. The size may be omitted, in which case a small starting size is allocated.

 

你可能感兴趣的:(golang之map排序)