用Collections.sort方法对list排序有两种方法
第一种是list中的对象实现Comparable接口,如下:
<strong>/**
02 * 根据order对User排序
03 */
04 public class User implements 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 public int compareTo(User arg0) {
20 return this.getOrder().compareTo(arg0.getOrder());
21 }
22 }
23 </strong>
测试一下:
输出结果如下
a
b
第二种方法是根据Collections.sort重载方法来实现,例如:
<strong>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 list = new ArrayList();
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 }</strong>
=
view source
<strong>/**
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 }</strong>
主类中这样写即可:
<strong>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 list = new ArrayList();
10 list.add(user2);
11 list.add(user1);
12
13 Collections.sort(list,new Comparator(){
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 }
23 </strong>
输出结果如下
a
b
前者代码结构简单,但是只能根据固定的属性排序,后者灵活,可以临时指定排序项,但是代码不够简洁
多字段的场合:
<strong>Collections.sort(list,new Comparator(){
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 });
19
20 </strong>
标签:sort,Java,name,list,public,User,return,order
From: https://blog.51cto.com/u_16203469/6838428