通过一个实例讲解 Collections.sort() 用法

Collections.sort() 方法应该是开发中最常用的排序方法吧!

下面通过一个例子讲解简单用法:

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
// 首先定义一个 POJO
public class User {

String name;

String age;

public User(String name, String age) {
this.name = name;
this.age = age;
}

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;
}
}

// 再定义 POJO 的比较类
import java.util.Comparator;

public class UserComparator implements Comparator {

public int compare(Object arg0, Object arg1) {
User user0 = (User) arg0;
User user1 = (User) arg1;
// 首先比较年龄,如果年龄相同,则比较名字
int flag = user0.getAge().compareTo(user1.getAge());
if (flag == 0) {
return user0.getName().compareTo(user1.getName());
} else {
return flag;
}
}
}

// 测试方法
public static void main(String[] args) {
List userlist = new ArrayList();
userlist.add(new User("dd", "4"));
userlist.add(new User("aa", "1"));
userlist.add(new User("ee", "5"));
userlist.add(new User("bb", "2"));
userlist.add(new User("ff", "5"));
userlist.add(new User("cc", "3"));
userlist.add(new User("gg", "6"));

UserComparator comparator = new UserComparator();
Collections.sort(userlist, comparator);

for (int i = 0; i < userlist.size(); i++) {
User user_temp = (User) userlist.get(i);
System.out.println(user_temp.getAge() + "," + user_temp.getName());
}

}

结果: