java的排序类 Collections

场景:比如说有一个List<Student> 里面有许多学生 我们想让这些学生按照年龄的大小排序

 

我们可以用java自带的 java.util.Collections 工具类来实现  

Collections.sort(rootList, studentComparator);

public Comparator<Student> studentComparator = new Comparator<Student>() {
        public int compare(Student o1, Student o2) {
            return o1.getAge() - o2.getAge();     //从小到大
        }
};

解释一下:sort方法  第一个是需要排序的list    第二个是排序的规则    规则是自己自定义的   

 

多个字段排序,比如先排年龄,年龄相同再排姓名  

 
 
Collections.sort(rootList, studentComparator);

public Comparator<Student> studentComparator = new Comparator<Student>() {
        public int compare(Student o1, Student o2) {
            int age=o1.getAge() - o2.getAge();
            if(age==0){
                return o1.getName() - o2.getName();
            }else{
                return age;
            }
        }
};

 

转载于:https://www.cnblogs.com/coder-lzh/p/8673089.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值