对List中对象的某个字段按照从大到小或者从小到大的顺序进行排序
看代码:
首先创建一个实体对象:
package com.sort;
class User {
String name;
String age;
String birthday;
public User(String name, String age, String birthday) {
this.name = name;
this.age = age;
this.birthday = birthday;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
}
然后组织数据,并进行排序:
package com.sort;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
public class SortTest {
public static void main(String[] args){
List<User> userlist=new ArrayList<User>();
userlist.add(new User("dd","4","2015-08-01"));
userlist.add(new User("aa","1","2015-08-01"));
userlist.add(new User("ee","5","2015-08-03"));
userlist.add(new User("bb","1","2015-08-04"));
userlist.add(new User("ff","5","2015-08-05"));
userlist.add(new User("cc","3","2015-08-06"));
userlist.add(new User("gg","6","2015-08-07"));
//直接调用Collections中的比较器,重写compare方法即可,不需要继承Comparable接口
Collections.sort(userlist, new Comparator<User>(){
@Override
public int compare(User o1, User o2) {
//首先比较日期大小,按照降序排列,如果要按照升序排列,只需修改成:
//int flag = o1.birthday.compareTo(o2.birthday);
int flag = o2.birthday.compareTo(o1.birthday);
if(flag==0){
//如果日期一致,则比较年龄大小按照升序排列
return o1.age.compareTo(o2.age);
}
return flag;
}
});
for (int i=0;i<userlist.size();i++){
User user_temp=(User)userlist.get(i);
System.out.println(user_temp.getAge()+","+user_temp.getName()+","+user_temp.birthday);
}
}
}
运行结果
6,gg,2015-08-07
3,cc,2015-08-06
5,ff,2015-08-05
2,bb,2015-08-04
5,ee,2015-08-03
1,aa,2015-08-01
4,dd,2015-08-01