sorting - 根据值(结构的属性)对 map 进行排序

标签 sorting go struct

我有下面的 map :

detail := make(map[string]*Log)

type Log struct {
    Id      []string
    Name    []string
    Priority   int   // value could be 1, 2, 3
    Message    string
}

我想根据在我的例子中是结构的值对“详细信息”映射进行排序。这应该按属性“优先级”排序。

例如,Log(结构映射)可能具有类似于以下的值:

Z : &{[ba60] [XYZ] 3 "I am the boss"}
B : &{[ca50] [ABC] 2 "I am the Junior"}
U : &{[zc20] [PQR] 1 "I am the Newbie"}

我希望他们按递增的优先级顺序打印,即 1 到 3

U : &{[zc20] [PQR] 1 "I am the Newbie"}
B : &{[ca50] [ABC] 2 "I am the Junior"}
Z : &{[ba60] [XYZ] 3 "I am the boss"}

我尝试使用排序并实现了排序接口(interface),但似乎仍然在某处遗漏了线索。所以,我实现了以下接口(interface):

type byPriority []*Log

func (d byPriority) Len() int {
    return len(d)
}
func (d byPriority) Less(i, j int) bool {
    return d[i].Priority < d[j].Priority
}
func (d byPriority) Swap(i, j int) {
    d[i], d[j] = d[j], d[i]
}

但是我应该如何在此 map 上应用 sort.Sort() 方法来获得排序结果。我需要添加更多代码吗?

最佳答案

Go 中的 map 类型是无序的。无论您对 map 做什么,下次您对其进行迭代时,您将收到随机顺序的 key 。因此无法对 map 进行“排序”。

您可以做的是将 map 的条目复制到一个可排序的 slice 中。

package main

import (
    "fmt"
    "sort"
)

type Log struct {
    Id       []string
    Name     []string
    Priority int // value could be 1, 2, 3
    Message  string
}

type Entry struct {
    key   string
    value *Log
}

type byPriority []Entry

func (d byPriority) Len() int {
    return len(d)
}
func (d byPriority) Less(i, j int) bool {
    return d[i].value.Priority < d[j].value.Priority
}
func (d byPriority) Swap(i, j int) {
    d[i], d[j] = d[j], d[i]
}

func printSorted(detail map[string]*Log) {
    // Copy entries into a slice.
    slice := make(byPriority, 0, len(detail))
    for key, value := range detail {
        slice = append(slice, Entry{key, value})
    }

    // Sort the slice.
    sort.Sort(slice)

    // Iterate and print the entries in sorted order.
    for _, entry := range slice {
        fmt.Printf("%s : %v\n", entry.key, entry.value)
    }
}

func main() {
    detail := map[string]*Log{
        "Z": &Log{[]string{"ba60"}, []string{"XYZ"}, 3, "I am the boss"},
        "B": &Log{[]string{"ca50"}, []string{"ABC"}, 2, "I am the Junior"},
        "U": &Log{[]string{"zc20"}, []string{"PQR"}, 1, "I am the Newbie"},
    }

    printSorted(detail)
}

关于sorting - 根据值(结构的属性)对 map 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49066606/

相关文章:

python - 什么算法解决方案可以匹配包含倍数的两个垃圾箱之间的项目?

java - 在循环中延迟重新绘制 JPanel

c - 如何打印数组中包含的结构元素

php - 如何在 PHP 中对数组和数据进行排序?

python - 移动列表的最后一个元素

xml - 从 XSD 生成 Go 结构

go - 从peer删除ChainCode

Go 自动类型转换 - 将 interface{} 与具体类型进行比较

struct - 如何创建不同类型的结构体数组的数组?

c - malloc 中的 Sigsegv