goland 排序
简介
goland 排序
对map进行排序
代码
package main
import (
"fmt"
"sort"
)
// 给key排序,从小到大
func Map(maps map[int]string) (keys []int) {
keys = []int{}
// 得到各个key
for key := range maps {
keys = append(keys, key)
}
// 给key排序,从小到大
sort.Sort(sort.IntSlice(keys)) // 或者 sort.Ints(keys)
// 如果key是字符串,可以使用sort.Strings(keys)
return
}
// 给key排序,从大到小
func Map2(maps map[int]string) (keys []int) {
keys = []int{}
// 得到各个key
for key := range maps {
keys = append(keys, key)
}
// 给key排序,从大到小
sort.Sort(sort.Reverse(sort.IntSlice(keys)))
return
}
func main() {
maps := map[int]string{
1: "星期一",
2: "星期二",
3: "星期三",
4: "星期四",
5: "星期五",
6: "星期六",
7: "星期天",
}
keys := Map2(maps)
// 遍历map
for _, key := range keys {
fmt.Printf("key = %v,value = %v\n", key, maps[key])
}
}
切片排序
代码
package main
import (
"fmt"
"sort"
)
type Person struct {
Name string
Age int
}
type ByNum []Person
func (a ByNum) Len() int { return len(a) }
func (a ByNum) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByNum) Less(i, j int) bool { return a[i].Age < a[j].Age }
func main() {
people := []Person{
{"Alice", 25},
{"Bob", 30},
{"Charlie", 20},
}
fmt.Println("Before sorting:")
fmt.Println(people)
sort.Sort(ByNum(people))
fmt.Println("After sorting:")
fmt.Println(people)
}