Java使用Comparator做CollectionsSort

Java使用Comparator做CollectionsSort

當Server Loading較低時,可以考慮原本在SQL使用ORDER BY排序的作法,
改使用在該物件內@Override compare方法,並使用Collections.sort();
來做排序,降低資料庫Loading。

物件範例-對Website、UserId排序

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
public class Example {

/* 避免 override compareTo 改用 comparator 比較有彈性 */
public final static Comparator<Example> websiteAndUserIdAscComparator = new Comparator<Example>() {

@Override
public int compare(Example o1, Example o2) {
int delta = Integer.compare(o1.getWebsite(), o2.getWebsite());

if (delta != 0) {
return delta;
}
return o1.getUserId().compareTo(o2.getUserId());
}

};

public final static Comparator<Example> websiteAscComparator = new Comparator<Example>() {

@Override
public int compare(Example o1, Example o2) {
return Integer.compare(o1.getWebsite(), o2.getWebsite());
}

};

public final static Comparator<Example> userIdAscComparator = new Comparator<Example>() {

@Override
public int compare(Example o1, Example o2) {
return o1.getUserId().compareTo(o2.getUserId());
}

};

public int website;

public String userId;

public Example(int website, String userId) {
super();

this.website = website;
this.userId = userId;
}

public int getWebsite() {
return website;
}

public String getUserId() {
return userId;
}
}

使用Collections.sort排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
List<Example> lList = new ArrayList<Example>();

lList.add(4, "user0004");
lList.add(1, "user0001");
lList.add(7, "user0007");
lList.add(2, "user0002");
lList.add(9, "user0009");
lList.add(1, "user0001");
lList.add(5, "user0005");

//對Website、UserId ASC排序
Collections.sort(lList, Example.websiteAndUserIdAscComparator);
//對Website ASC排序
Collections.sort(lList, Example.websiteAscComparator);
//對UserId ASC排序
Collections.sort(lList, Example.userIdAscComparator);