List 排序

package cn.dingyuegroup.dayu.management.service.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Students {
      
    private int age;  
    private int score;  
      
    public Students(int age, int score){  
        super();  
        this.age = age;  
        this.score = score;  
    }  
      
    public int getAge() {  
        return age;  
    }  
    public void setAge(int age) {  
        this.age = age;  
    }  
    public int getScore() {  
        return score;  
    }  
    public void setScore(int score) {  
        this.score = score;  
    }


    public static void main(String[] args) {
        List<Students> students = new ArrayList<Students>();
        students.add(new Students(23, 100));
        students.add(new Students(27, 98));
        students.add(new Students(29, 99));
        students.add(new Students(29, 98));
        students.add(new Students(22, 89));
        // 第一种排序方式
        students.sort(Comparator.comparingInt(Students::getAge));
        // 第二种自定义排序
        Collections.sort(students, new Comparator<Students>() {
            @Override
            public int compare(Students o1, Students o2) {
                // o2-o1  降序  o1-o2 升序
                int i =  o2.getScore() - o1.getScore(); 
                //  等于的情况在按年龄排序
                if(i == 0){
                    return o1.getAge() - o2.getAge();
                }
                return i;
            }
        });
        for(Students stu : students){
            System.out.println("score:" + stu.getScore() + ":age" + stu.getAge());
        }
    }

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值