Collections.sort(List<T> list):元素需實作 Comparable<T>Collections.sort(List<T> list, Comparator<? super T> c):外部比較器策略list.sort(comparator)、Comparator.comparing(...) 鏈式寫法package com.tom.compare;
import java.util.*;
public class CompareClient {
public static void main(String[] args) {
List<Content> list = new ArrayList<>();
list.add(new Content(15000, "1asdfasd5000"));
list.add(new Content(10000, "10000"));
list.add(new Content(20000, "20000"));
list.add(new Content(30000, "30000"));
list.add(new Content(25000, "25000"));
list.add(new Content(13000, "13000"));
list.add(new Content(15000, "15000"));
list.add(new Content(89000, "89000"));
Collections.sort(list, new ContentComparator());
for (Content c : list) {
System.out.println("content.getName() " + c.getName());
}
}
}
class ContentComparator implements Comparator<Content> {
@Override
public int compare(Content c1, Content c2) {
return Long.compare(c1.getKey(), c2.getKey()); // Java 7+ 推薦寫法
// 等同於:
// if (c1.getKey() > c2.getKey()) return 1;
// else if (c1.getKey() == c2.getKey()) return 0;
// else return -1;
}
}
class Content {
private long key;
private String name;
public Content(long key, String name) {
this.key = key;
this.name = name;
}
// getter/setter 略...
}
content.getName() 10000 content.getName() 13000 content.getName() 1asdfasd5000 content.getName() 15000 content.getName() 15000 content.getName() 20000 content.getName() 25000 content.getName() 30000 content.getName() 89000
依 key 升冪排序,相同 key 維持原順序(穩定排序)。
// Lambda 表達式
list.sort((c1, c2) -> Long.compare(c1.getKey(), c2.getKey()));
// Comparator 靜態工廠方法鏈式調用
list.sort(Comparator.comparing(Content::getKey));
// 多鍵值排序:先按 key 升冪,再按 name 降冪
list.sort(Comparator
.comparing(Content::getKey)
.thenComparing(Content::getName, Comparator.reverseOrder()));
// 空值安全
list.sort(Comparator.nullsFirst(Comparator.comparing(Content::getKey)));
| 場景 | 推薦方式 |
|---|---|
| 類別有「自然順序」(如 ID、日期) | 實作 Comparable<T> |
| 需要多種排序規則 | 建立多個 Comparator 實作 |
| 無法修改類別源碼(第三方類) | 只能用 Comparator |
| 一次性臨時排序 | Lambda/匿名類別 Comparator |
compare(a,b) 與 compare(b,a) 必須號相反,違反會導致排序錯誤或拋出 IllegalArgumentExceptionreturn c1.key - c2.key 可能溢位,必須用 Long.compare() 或條件判斷nullsFirst/Last 或比較器內部處理