用Collections.sort方法对list排序有两种方法
第一种是list中的对象实现Comparable接口,如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
/** * 根据order对User排序 */ public class User implements Comparable
<user>
{
private String name;
private Integer order;
public String getName() {
return name;
}
public void setName(String name) {
this .name = name;
}
public Integer getOrder() {
return order;
}
public void setOrder(Integer order) {
this .order = order;
}
public int compareTo(User arg0) {
return this .getOrder().compareTo(arg0.getOrder());
}
} </user>
|
测试一下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
public class Test{
public static void main(String[] args) {
User user1 = new User();
user1.setName( "a" );
user1.setOrder( 1 );
User user2 = new User();
user2.setName( "b" );
user2.setOrder( 2 );
List
<user>
list = new ArrayList
<user>
();
//此处add user2再add user1
list.add(user2);
list.add(user1);
Collections.sort(list);
for (User u : list){
System.out.println(u.getName());
}
}
} </user>
</user>
|
输出结果如下
a
b
第二种方法是根据Collections.sort重载方法来实现,例如:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
/** * 根据order对User排序 */ public class User { //此处无需实现Comparable接口
private String name;
private Integer order;
public String getName() {
return name;
}
public void setName(String name) {
this .name = name;
}
public Integer getOrder() {
return order;
}
public void setOrder(Integer order) {
this .order = order;
}
} |
主类中这样写即可:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
public class Test{
public static void main(String[] args) {
User user1 = new User();
user1.setName( "a" );
user1.setOrder( 1 );
User user2 = new User();
user2.setName( "b" );
user2.setOrder( 2 );
List
<user>
list = new ArrayList
<user>
();
list.add(user2);
list.add(user1);
Collections.sort(list, new Comparator
<user>
(){
public int compare(User arg0, User arg1) {
return arg0.getOrder().compareTo(arg1.getOrder());
}
});
for (User u : list){
System.out.println(u.getName());
}
}
} </user>
</user>
</user>
|
输出结果如下
a
b
前者代码结构简单,但是只能根据固定的属性排序,后者灵活,可以临时指定排序项,但是代码不够简洁
多字段的场合:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
Collections.sort(list, new Comparator
<user>
(){
public int compare(User arg0, User arg1) {
// 第一次比较专业
int i = arg0.getOrder().compareTo(arg1.getOrder());
// 如果专业相同则进行第二次比较 if (i== 0 ){
// 第二次比较 int j=arg0.getXXX().compareTo(arg1.getXXX());
// 如果学制相同则返回按年龄排序 if (j== 0 ){
return arg0.getCCC().compareTo(arg1.getCCC());
}
return j;
}
return i;
}
});
</user>
|