Collect values in order, each containing a map

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

Leave a Comment