http://www.open-open.com/lib/view/open1322614659562.html
用Collections.sort方法对list排序有两种方法
第一种是list中的对象实现Comparable
接口,如下:
01
/**
02
* 根据order对User排序
03
*/
04
public class User implements Comparable<user>{
05
private String name;
06
private Integer order;
07
public String getName() {
08
return name;
09
}
10
public void setName(String name) {
11
this.name = name;
12
}
13
public Integer getOrder() {
14
return order;
15
}
16
public void setOrder(Integer order) {
17
this.order = order;
18
}
19
public int compareTo(User arg0) {
20
return this.getOrder().compareTo(arg0.getOrder());
21
}
22
}</user>
测试一下:
01
public class Test{
02
03
public static void main(String[] args) {
04
User user1 = new User();
05
user1.setName("a");
06
user1.setOrder(1);
07
User user2 = new User();
08
user2.setName("b");
09
user2.setOrder(2);
10
List<user> list = new ArrayList<user>();
11
//此处add user2再add user1
12
list.add(user2);
13
list.add(user1);
14
Collections.sort(list);
15
for(User u : list){
16
System.out.println(u.getName());
17
}
18
}
19
}</user></user>
输出结果如下
a
b
第二种方法是根据Collections.sort
重载方法来实现,例如:
01
/**
02
* 根据order对User排序
03
*/
04
public class User { //此处无需实现Comparable接口
05
private String name;
06
private Integer order;
07
public String getName() {
08
return name;
09
}
10
public void setName(String name) {
11
this.name = name;
12
}
13
public Integer getOrder() {
14
return order;
15
}
16
public void setOrder(Integer order) {
17
this.order = order;
18
}
19
}
主类中这样写即可:
01
public class Test{
02
public static void main(String[] args) {
03
User user1 = new User();
04
user1.setName("a");
05
user1.setOrder(1);
06
User user2 = new User();
07
user2.setName("b");
08
user2.setOrder(2);
09
List<user> list = new ArrayList<user>();
10
list.add(user2);
11
list.add(user1);
12
13
Collections.sort(list,new Comparator<user>(){
14
public int compare(User arg0, User arg1) {
15
return arg0.getOrder().compareTo(arg1.getOrder());
16
}
17
});
18
for(User u : list){
19
System.out.println(u.getName());
20
}
21
}
22
}</user></user></user>
输出结果如下
a
b
前者代码结构简单,但是只能根据固定的属性排序,后者灵活,可以临时指定排序项,但是代码不够简洁
多字段的场合:
view sourceprint?
01
Collections.sort(list,new Comparator<user>(){
02
public int compare(User arg0, User arg1) {
03
// 第一次比较专业
04
int i = arg0.getOrder().compareTo(arg1.getOrder());
05
06
// 如果专业相同则进行
第二次比较
07
if(i==0){
08
// 第二次比较
09
int j=arg0.getXXX().compareTo(arg1.getXXX());
10
// 如果学制相同则返回按年龄排序
11
if(j==0){
12
return arg0.getCCC().compareTo(arg1.getCCC());
13
}
14
return j;
15
}
16
return i;
17
}
18
});</user>