Java 8 golang 1.8_golang 排序 1.8 新特性

1.8以前是使用

//数组对象实现该接口

type Interface interface {

// Len is the number of elements in the collection.

Len() int

// Less reports whether the element with

// index i should sort before the element with index j.

Less(i, j int) bool

// Swap swaps the elements with indexes i and j.

Swap(i, j int)

}

//然后使用

sort.Sort(interface)

//例如

type StringList []string

func (sl StringList )Len() int{

return len(sl)

}

func (sl StringList )Less(i, j int) bool{

return sl[i]

}

func (sl StringList )Swap(i, j int){

var temp string = sl[i]

sl[i] = sl[j]

sl[j] = temp

}

b := StringList{"4","6","5"}

sort.Sort(b)

fmt.Println(b)

1.8新增sort.Slice函数就方便好多了

sort.Slice(s,func(i,j int)bool {return s [i] .Name

a := []string{"1","3","2"}

sort.Slice(a, func(i,j int) bool { return a[i]>a[j]});

完整例子

type StringList []string

func (sl StringList )Len() int{

return len(sl)

}

func (sl StringList )Less(i, j int) bool{

return sl[i]

}

func (sl StringList )Swap(i, j int){

var temp string = sl[i]

sl[i] = sl[j]

sl[j] = temp

}

func main() {

TestSort()

}

func TestSort(){

a := []string{"1","3","2"}

sort.Slice(a, func(i,j int) bool { return a[i]>a[j]});

fmt.Println(a)

b := StringList{"4","6","5"}

sort.Sort(b)

fmt.Println(b)

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值