Go对象切片排序与map排序

对象切片排序

在Go语言中,对对象切片进行排序的基本步骤如下:

  1. 定义对象类型
  2. 实现sort.Interface接口
  3. 实现Less方法,该方法定义了对象的比较规则
  4. 使用sort包中的sort方法,进行排序
    举例:
package main

import (
	"fmt"
	"sort"
)

type Employee struct {
	Name string
	Age  int
}

type Employees []Employee

func (s Employees) Len() int {
	return len(s)
}

func (s Employees) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func (s Employees) Less(i, j int) bool {
	return s[i].Age < s[j].Age
}

func main() {
	staffs := []Employee{
		{Name: "Peter", Age: 18},
		{Name: "Mike", Age: 20},
		{Name: "Rose", Age: 12},
		{Name: "Jake", Age: 14},
		{Name: "Bill", Age: 10},
	}
	sort.Sort(Employees(staffs))
	for i := range staffs {
		fmt.Println(staffs[i].Name, staffs[i].Age)
	}
}

运行结果:
Bill 10
Rose 12
Jake 14
Peter 18
Mike 20
按照员工的年龄从小到大对员工列表进行排序输出。

map根据值进行排序

在Go语言中,map是无序的,因此不能直接对map的值进行排序。可以将map中的值提取出来,转化为切片,然后针对切片进行排序。具体实现步骤如下:

  1. 从map中提取所有值放到切片中。
  2. 实现一个sort.Interface接口的类型,该类型代表一个map值所具有的的属性
  3. 使用sort.Sort方法,根据Person实现的排序规则对切片进行排序。
    举例:
type Person struct {
	Name string
	Age  int
}

type ByAge []Person

func (a ByAge) Len() int {
	return len(a)
}

func (a ByAge) Swap(i, j int) {
	a[i], a[j] = a[j], a[i]
}

func (a ByAge) Less(i, j int) bool {
	return a[i].Age < a[j].Age
}

func main() {
	ages := map[string]int{
		"Peter": 18,
		"Mike":  20,
		"Rose":  12,
		"Jake":  14,
		"Bill":  10,
	}
	people := make([]Person, len(ages))
	i := 0
	for k, v := range ages {
		people[i] = Person{k, v}
		i++
	}
	sort.Sort(ByAge(people))
	for _, person := range people {
		fmt.Printf("%s\t%d\n", person.Name, person.Age)
	}
}

运行结果:
Bill 10
Rose 12
Jake 14
Peter 18
Mike 20
按照人员的年龄从小到大对map的值进行排序输出。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值