文章目录
  1. 1. Map 根据键名排序
  2. 2. Map 根据键值排序

Map 根据键名排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
var keys []int
for k := range m {
keys = append(keys, k)
}
sort.Ints(keys)

// To perform the opertion you want
for _, k := range keys {
fmt.Println("Key:", k, "Value:", m[k])
}
}

Map 根据键值排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package tools

import (
"sort"
)

type Map struct {
Key string
Value int
}

type MapSlice []Map

func (m MapSlice) Len() int { return len(m) }
func (m MapSlice) Less(i, j int) bool { return m[i].Value < m[j].Value }
func (m MapSlice) Swap(i, j int) { m[i], m[j] = m[j], m[i] }

func Sort(m map[string]int) MapSlice {
ms := make(MapSlice, 0)
for k, v := range m {
ms = append(ms, Map{k, v})
}
sort.Sort(ms)

return ms
}

func SortReverse(m map[string]int) MapSlice {
ms := make(MapSlice, 0)
for k, v := range m {
ms = append(ms, Map{k, v})
}
sort.Sort(sort.Reverse(ms))

return ms
}
文章目录
  1. 1. Map 根据键名排序
  2. 2. Map 根据键值排序