首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java List 排序完全指南:Collections.sort 與 Comparator 實戰

     編輯:Java 相關知識

核心 API

  • Collections.sort(List<T> list):元素需實作 Comparable<T>
  • Collections.sort(List<T> list, Comparator<? super T> c):外部比較器策略
  • Java 8+: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 維持原順序(穩定排序)。

Java 8+ 現代寫法


// 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)));

Comparable vs Comparator 選擇指南

場景推薦方式
類別有「自然順序」(如 ID、日期)實作 Comparable<T>
需要多種排序規則建立多個 Comparator 實作
無法修改類別源碼(第三方類)只能用 Comparator
一次性臨時排序Lambda/匿名類別 Comparator

常見陷阱與最佳實踐

  1. 比較器一致性:compare(a,b) 與 compare(b,a) 必須號相反,違反會導致排序錯誤或拋出 IllegalArgumentException
  2. 避免減法溢位:return c1.key - c2.key 可能溢位,必須用 Long.compare() 或條件判斷
  3. 不可變鍵值:排序依賴的欄位在排序過程中不應被修改
  4. Null 安全:列表含 null 時需使用 nullsFirst/Last 或比較器內部處理
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved