Go map如何排序

1. 将key 或 value 单独组成其类型的切片或数组,进行排序

go 复制代码
package main

import (
	"fmt"
	"sort"
)

func main() {
	table := map[string]string{
		"hello": "hello",
		"world": "world",
		"a":     "a",
		"b":     "b",
		"c":     "c",
		"d":     "d",
	}

	var keys, values []string

	for k, v := range table {
		keys = append(keys, k)
		values = append(values, v)
	}

	sort.Slice(keys, func(i, j int) bool {
		if keys[i] < keys[j] {
			//keys[i], keys[j] = keys[j], keys[i]
			values[i], values[j] = values[j], values[i]
			return true
		}
		return false
	})

	fmt.Println(keys)
	fmt.Println(values)
}

可以根据有序的key,找到对应的value

go 复制代码
    for _, key := range keys {
         fmt.Println(table[key])
    }

2. 将key,value放入结构体,对结构体切片排序,既可以对key排序,又可以对value排序

go 复制代码
	type Entity struct {
		K string
		V string
	}
	
	table := map[string]string{
		"hello": "hello",
		"world": "world",
		"a":     "a",
		"b":     "b",
		"c":     "c",
		"d":     "d",
	}

	var entities []Entity
	
	for k, v := range table {
		entities = append(entities, Entity{k, v})
	}

	sort.Slice(entities, func(i, j int) bool {
		return entities[i].K < entities[j].K
	})

	fmt.Println(entities)
相关推荐
Tomhex4 小时前
Go泛型实战:类型参数化应用
golang
AnYU_14 小时前
布隆过滤器(BloomFilter)
golang·bloomfilter·shorturl
abcefg_h6 小时前
GORM——基础介绍与CRUD
开发语言·后端·golang
geovindu8 小时前
go:Decorator Pattern
开发语言·设计模式·golang·装饰器模式
anzhxu17 小时前
Go基础之环境搭建
开发语言·后端·golang
ILYT NCTR20 小时前
搭建Golang gRPC环境:protoc、protoc-gen-go 和 protoc-gen-go-grpc 工具安装教程
开发语言·后端·golang
叹一曲当时只道是寻常1 天前
memos-cli 安装与使用教程:将 Memos 笔记同步到本地并支持 AI 语义搜索
人工智能·笔记·golang
geovindu1 天前
go: Facade Pattern
设计模式·golang·外观模式
小众AI1 天前
Go 多账户 WebDAV 服务实现
golang
念何架构之路1 天前
图解defer
开发语言·后端·golang