Sort Go map values by keys

后端 未结 6 623
悲哀的现实
悲哀的现实 2020-11-28 02:58

When iterating through the returned map in the code, returned by the topic function, the keys are not appearing in order.

How can I get the keys to be in order / sor

6条回答
  •  囚心锁ツ
    2020-11-28 03:19

    The Go blog: Go maps in action has an excellent explanation.

    When iterating over a map with a range loop, the iteration order is not specified and is not guaranteed to be the same from one iteration to the next. Since Go 1 the runtime randomizes map iteration order, as programmers relied on the stable iteration order of the previous implementation. If you require a stable iteration order you must maintain a separate data structure that specifies that order.

    Here's my modified version of example code: http://play.golang.org/p/dvqcGPYy3-

    package main
    
    import (
        "fmt"
        "sort"
    )
    
    func main() {
        // To create a map as input
        m := make(map[int]string)
        m[1] = "a"
        m[2] = "c"
        m[0] = "b"
    
        // To store the keys in slice in sorted order
        keys := make([]int, len(m))
        i := 0
        for k := range m {
            keys[i] = k
            i++
        }
        sort.Ints(keys)
    
        // To perform the opertion you want
        for _, k := range keys {
            fmt.Println("Key:", k, "Value:", m[k])
        }
    }
    

    Output:

    Key: 0 Value: b
    Key: 1 Value: a
    Key: 2 Value: c
    

提交回复
热议问题