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

Java Map 排序完整指南:TreeMap、HashMap 按鍵值排序實戰

     編輯:Java 相關知識

前言

在統計報表等場景中,常需對 Map 進行排序。本文詳細講解 Java 主流 Map 實現的特性,並示範如何按 Key 或 Value 排序,附完整程式碼範例。

1. 常見 Map 實現比較

實現類特性同步Key/Value 可否為 null
HashMap最常用,基於 HashCode 存取,速度最快非同步Key 允許一個 null,Value 允許多個 null
TreeMap按 Key 自然順序或 Comparator 排序非同步Key 不允許 null
Hashtable類似 HashMap,但同步,效能較差同步Key/Value 皆不允許 null
LinkedHashMap保持插入順序或存取順序非同步Key/Value 允許 null

2. TreeMap 按 Key 排序(預設升序)

Map<String, String> map = new TreeMap<>();
map.put("c", "ccccc");
map.put("a", "aaaaa");
map.put("b", "bbbbb");
map.put("d", "ddddd");
// 遍歷輸出:a, b, c, d

3. TreeMap 自定義 Key 降序排序

Map<String, String> map = new TreeMap<>(new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
        return o2.compareTo(o1); // 降序
    }
});
map.put("c", "ccccc");
map.put("a", "aaaaa");
map.put("b", "bbbbb");
map.put("d", "ddddd");
// 輸出:d, c, b, a

4. 按 Value 排序(適用 TreeMap、HashMap)

將 entrySet() 轉為 List,再用 Collections.sort 配合 Comparator。

Map<String, String> map = new HashMap<>();
map.put("c", "ccccc");
map.put("a", "aaaaa");
map.put("b", "bbbbb");
map.put("d", "ddddd");

List<Map.Entry<String, String>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
    @Override
    public int compare(Entry<String, String> o1, Entry<String, String> o2) {
        return o1.getValue().compareTo(o2.getValue()); // 升序
    }
});

for (Map.Entry<String, String> entry : list) {
    System.out.println(entry.getKey() + ":" + entry.getValue());
}
// 輸出:a:aaaaa, b:bbbbb, c:ccccc, d:ddddd

5. Java 8 Stream 寫法(更簡潔)

// 按 Key 排序
map.entrySet().stream()
    .sorted(Map.Entry.comparingByKey())
    .forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));

// 按 Value 排序
map.entrySet().stream()
    .sorted(Map.Entry.comparingByValue())
    .forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));

6. 總結

  • 需保持 Key 有序 → 直接用 TreeMap。
  • 需按 Value 排序 → 轉 List 後 Collections.sort 或 Stream API。
  • 多執行緒環境 → 考慮 ConcurrentHashMap 或 Collections.synchronizedMap。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved