-
Notifications
You must be signed in to change notification settings - Fork 4
/
map.go
47 lines (38 loc) · 996 Bytes
/
map.go
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
37
38
39
40
41
42
43
44
45
46
47
package goutils
import (
"sort"
)
// MapIntIntSortedKeys 返回map[int]int{}按value排序的keys
func MapIntIntSortedKeys(m map[int]int, desc bool) []int {
keys := make([]int, 0, len(m))
for key := range m {
keys = append(keys, key)
}
sort.SliceStable(keys, func(i, j int) bool {
if m[keys[i]] == m[keys[j]] { // 如果值相同,就按照key的大小排序
return keys[i] < keys[j]
}
if desc {
return m[keys[i]] > m[keys[j]]
}
return m[keys[i]] < m[keys[j]]
})
return keys
}
// MapStrIntSortedKeys 返回map[string]int{}按value排序的keys
func MapStrIntSortedKeys(m map[string]int, desc bool) []string {
keys := make([]string, 0, len(m))
for key := range m {
keys = append(keys, key)
}
sort.SliceStable(keys, func(i, j int) bool {
if m[keys[i]] == m[keys[j]] { // 如果值相同,就按照key的字典序排序
return keys[i] < keys[j]
}
if desc {
return m[keys[i]] >= m[keys[j]]
}
return m[keys[i]] < m[keys[j]]
})
return keys
}