go - 按顺序收集值,每个值都包含一个映射

标签 go hashmap

在代码中迭代返回的map时,由topic函数返回,key没有按顺序出现。

如何让键按顺序排列/对 map 进行排序,以便键按顺序排列且值对应?

这里是 the code .

最佳答案

Go blog: Go maps in action有很好的解释。

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.

这是我修改后的示例代码版本: 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])
    }
}

输出:

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

关于go - 按顺序收集值,每个值都包含一个映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23330781/

相关文章:

Java - 在重载的构造函数调用中创建 HashMap

go - 使用 go run 的路径不适用于 go install/从 bin 调用可执行文件

go - 可变参数函数的困难

java - HashMap - 不返回相等键的正确值

java - 更新 ArrayList<HashMap<String, ?>>

java - 如何在java中获取映射中对(键)值的总和?

java - hashmap自定义类键&&对象保存/加载

go - 一个通用的 http 处理程序而不是几个

compiler-construction - if-else undefined variable 编译错误

go - 系统单位文件始终失败