java List对象排序

java List 排序 Collections.sort() 对 List 排序

 1 //一个POJO例子
 2 
 3 class User {
 4  String name;
 5  String age;
 6  
 7  public User(String name,String age){
 8   this.name=name;
 9   this.age=age;
10  }
11  public String getAge() {
12   return age;
13  }
14  public void setAge(String age) {
15   this.age = age;
16  }
17  public String getName() {
18   return name;
19  }
20  public void setName(String name) {
21   this.name = name;
22  } 
23 }
24 
25 
26 //具体的比较类,实现Comparator接口
27 
28 import java.util.Comparator;
29 import java.util.List;
30 import java.util.ArrayList;
31 import java.util.Collections;
32 
33 public class ComparatorUser implements Comparator{
34 
35  public int compare(Object arg0, Object arg1) {
36   User user0=(User)arg0;
37   User user1=(User)arg1;
38 
39    //首先比较年龄,如果年龄相同,则比较名字
40 
41   int flag=user0.getAge().compareTo(user1.getAge());
42   if(flag==0){
43    return user0.getName().compareTo(user1.getName());
44   }else{
45    return flag;
46   }  
47  }
48  
49 }
50 
51 
52 
53 
54 //测试类
55 public class SortTest {
56 
57  
58  public static void main(String[] args){
59   List userlist=new ArrayList();
60   userlist.add(new User("dd","4"));
61   userlist.add(new User("aa","1"));
62   userlist.add(new User("ee","5"));
63   userlist.add(new User("bb","2"));  
64   userlist.add(new User("ff","5"));
65   userlist.add(new User("cc","3"));
66   userlist.add(new User("gg","6"));
67   
68   ComparatorUser comparator=new ComparatorUser();
69   Collections.sort(userlist, comparator);
70    
71   for (int i=0;i<userlist.size();i++){
72    User user_temp=(User)userlist.get(i);
73       System.out.println(user_temp.getAge()+","+user_temp.getName()); 
74   }
75   
76  }
77 }
78 
79  //首先年龄排序,如果年龄相同,则按名字排序
80 
81 结果:
82    1, aa
83    2, bb
84    3, cc
85    4, dd
86    5, ee                    //注意:同样是5岁的人,则比较名字(ee,ff),然后排序
87    5, ff
88    6, gg

再举一个例子:

1.现有对象

 1 List<Map<String, Object>> loanPayList= new ArrayList<Map<String, Object>>(loanPayList.size());

2.实现Comparator接口

 1     class LoanPayComparator implements Comparator<Object>{
 2         @SuppressWarnings("unchecked")
 3         public int compare(Object obj1, Object obj2) {
 4             Date d1 = (Date) ((Map<String, ?>) obj1).get(OTS_LOAN_PAY_BY_DATE);
 5             Date d2 = (Date) ((Map<String, ?>) obj2).get(OTS_LOAN_PAY_BY_DATE);
 6             if (d1 == null || d2 == null) {
 7                 LOG.warn("[loanPayComparator:compare()] sorted date is null.");
 8                 return 0;
 9             } else {
10                 if ((d1.getTime()) < d2.getTime()) {
11                     return 1;
12                 } else if ((d1.getTime()) > d2.getTime()) {
13                     return -1;
14                 } else {
15                     return 0;
16                 }
17             }
18         }
19     }

 3.排序

1 Collections.sort(loanPayList, new LoanPayComparator());

 

 

你可能感兴趣的:(java List对象排序)