在統計報表等場景中,常需對 Map 進行排序。本文詳細講解 Java 主流 Map 實現的特性,並示範如何按 Key 或 Value 排序,附完整程式碼範例。
| 實現類 | 特性 | 同步 | Key/Value 可否為 null |
|---|---|---|---|
| HashMap | 最常用,基於 HashCode 存取,速度最快 | 非同步 | Key 允許一個 null,Value 允許多個 null |
| TreeMap | 按 Key 自然順序或 Comparator 排序 | 非同步 | Key 不允許 null |
| Hashtable | 類似 HashMap,但同步,效能較差 | 同步 | Key/Value 皆不允許 null |
| LinkedHashMap | 保持插入順序或存取順序 | 非同步 | Key/Value 允許 null |
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
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
將 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
// 按 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()));
TreeMap。Collections.sort 或 Stream API。ConcurrentHashMap 或 Collections.synchronizedMap。