Java 集合框架透過 Comparator 介面支援自訂排序邏輯。本文示範如何實作 Comparator 對自訂物件進行降序排序,並使用 Collections.sort() 完成排序操作。
import java.util.*;
class Elem {
private int value;
public Elem(int v) { this.value = v; }
public int getValue() { return value; }
@Override public String toString() { return String.valueOf(value); }
}
class DescComparator implements Comparator {
@Override
public int compare(Elem o1, Elem o2) {
return Integer.compare(o2.getValue(), o1.getValue()); // 降序
}
}
public class VectorSortDemo {
public static void main(String[] args) {
List list = new Vector<>();
list.add(new Elem(1));
list.add(new Elem(22));
list.add(new Elem(3));
list.add(new Elem(14));
System.out.println("排序前:" + list);
Collections.sort(list, new DescComparator());
System.out.println("降序後:" + list);
}
}
// 降序
list.sort((a, b) -> Integer.compare(b.getValue(), a.getValue()));
// 或使用 Comparator 靜態方法
list.sort(Comparator.comparingInt(Elem::getValue).reversed());
list.sort(
Comparator.comparing(Elem::getCategory)
.thenComparingInt(Elem::getValue).reversed()
);
自訂物件排序、多欄位排序、動態排序規則(依使用者偏好切換升降序)、非自然順序排序需求。