List<Object> sort 排序

一个简单的 对象List 排序代码,按Cat.Uid 字母从高到底顺序sort

  1 import java.util.ArrayList;
  2 import java.util.Collections;
  3 import java.util.List;
  4 
  5 public class TestObjectComparable {
  6 
  7     @SuppressWarnings("unchecked")
  8     public static void main(String[] args) {
  9         // TODO Auto-generated method stub
 10         List<Cat> catList = new ArrayList<Cat>();
 11         
 12         Cat cat1 = new Cat("cat1","Z5");
 13         Cat cat2 = new Cat("cat2","Z7");
 14         Cat cat3 = new Cat("cat3","Z6");
 15         Cat cat4 = new Cat("cat4","Z2");
 16         Cat cat5 = new Cat("cat5","Z4");
 17         Cat cat6 = new Cat("cat6","Z3");
 18         Cat cat7 = new Cat("cat7","Z2");
 19         Cat cat8 = new Cat("cat7","Z6");
 20         
 21         catList.add(cat1);
 22         catList.add(cat2);
 23         catList.add(cat3);
 24         catList.add(cat4);
 25         catList.add(cat5);
 26         catList.add(cat6);
 27         catList.add(cat7);
 28         catList.add(cat8);
 29         
 30         for(Cat cat : catList){
 31             System.out.println(cat.getName() +"  "+cat.getUid());
 32         }
 33         
 34         System.out.println("==========");
 35         
 36          Collections.sort(catList); 
 37          
 38          
 39          for(Cat cat : catList){
 40                 System.out.println(cat.getName() +"  "+cat.getUid());
 41         }
 42          
 43          
 44 
 45     }
 46 
 47 }
 48 
 49 class Cat implements Comparable{
 50     
 51     private String name;
 52     private String uid;
 53     
 54     public Cat(String name,String uid){
 55         this.name=name;
 56         this.uid=uid;
 57     }
 58 
 59     @Override
 60     public int compareTo(Object o) {
 61         // TODO Auto-generated method stub
 62         Cat cat = (Cat) o;
 63         String uid = cat.getUid();
 64         
 65         return -this.uid.compareTo(uid);
 66     }
 67 
 68     public String getName() {
 69         return name;
 70     }
 71 
 72     public void setName(String name) {
 73         this.name = name;
 74     }
 75 
 76     public String getUid() {
 77         return uid;
 78     }
 79 
 80     public void setUid(String uid) {
 81         this.uid = uid;
 82     }
 83     
 84     
 85     
 86 }
 87 
 88 
 89 console输出
 90 cat1  Z5
 91 cat2  Z7
 92 cat3  Z6
 93 cat4  Z2
 94 cat5  Z4
 95 cat6  Z3
 96 cat7  Z2
 97 cat7  Z6
 98 ==========
 99 cat2  Z7
100 cat3  Z6
101 cat7  Z6
102 cat1  Z5
103 cat5  Z4
104 cat6  Z3
105 cat4  Z2
106 cat7  Z2

 

转载于:https://www.cnblogs.com/wahaha603/p/7232969.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值