Java list 对象 排序

  1. public class Students {  
  2.       
  3.     private int age;  
  4.     private int score;  
  5.       
  6.     public Students(int age, int score){  
  7.         super();  
  8.         this.age = age;  
  9.         this.score = score;  
  10.     }  
  11.       
  12.     public int getAge() {  
  13.         return age;  
  14.     }  
  15.     public void setAge(int age) {  
  16.         this.age = age;  
  17.     }  
  18.     public int getScore() {  
  19.         return score;  
  20.     }  
  21.     public void setScore(int score) {  
  22.         this.score = score;  
  23.     }  
  24. }  
  25. public static void main(String[] args) {  
  26.         List<Students> students = new ArrayList<Students>();  
  27.         students.add(new Students(23100));  
  28.         students.add(new Students(2798));  
  29.         students.add(new Students(2999));  
  30.         students.add(new Students(2998));  
  31.         students.add(new Students(2289));  
  32.         Collections.sort(students, new Comparator<Students>() {  
  33.        // getScore() 排序字段
  34.             @Override  
  35.             public int compare(Students o1, Students o2) {  
  36.                 int i = o1.getScore() - o2.getScore();  // 按照分数排序
  37.                 if(i == 0){  
  38.                     return o1.getAge() - o2.getAge();  // 按照年龄排序
  39.                 }  
  40.                 return i;  
  41.             }  
  42.         });  
  43.         for(Students stu : students){  
  44.             System.out.println(”score:” + stu.getScore() + “:age” + stu.getAge());  
  45.         }  
  46. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值