Go map如何排序

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

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

    for _, key := range keys {
         fmt.Println(table[key])
    }

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

	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)

你可能感兴趣的:(Go,golang)