44

In Go, what's the easiest way to get the keys in a map sorted alphabetically? This is the shortest way I can do it:

package main

import "container/vector"
import "fmt"
import "sort"

func main() {
    m := map[string]string {"b":"15", "z":"123123", "x":"sdf", "a":"12"}
    var keys vector.StringVector;
    for k,_ := range ( m ) {
            keys.Push(k)
    }
    sort.Sort( &keys )
    fmt.Printf("%v\n", keys)
}
4

2 回答 2

56

You are sorting an array of strings using StringVector. To minimize overhead, you could sort an array of strings.

package main

import (
    "fmt"
    "sort"
)

func main() {
    m := map[string]string{"b": "15", "z": "123123", "x": "sdf", "a": "12"}
    mk := make([]string, len(m))
    i := 0
    for k, _ := range m {
        mk[i] = k
        i++
    }
    sort.Strings(mk)
    fmt.Println(mk)
}

Output:

[a b x z]
于 2010-01-10T23:59:09.977 回答
16

That would be most elegant method:

package main

import (
    "fmt"
    "sort"
)

func main() {
    m := map[string]string{"b": "15", "z": "123123", "x": "sdf", "a": "12"}
    keys := make([]string, 0, len(m))
    for key := range m {
        keys = append(keys, key)
    }
    sort.Strings(keys)
    fmt.Println(keys)
}
于 2014-06-08T07:55:48.640 回答