Java Map 本身無序(除 LinkedHashMap、TreeMap),若需依「值」大小排序並保留鍵值對應,常見做法是轉為 Entry[] 陣列後用 Arrays.sort() 配合自訂 Comparator。
import java.util.*;
public class MapSortUtils {
@SuppressWarnings("unchecked")
public static Map.Entry[] sortByValueAsc(Map map) {
Set<Map.Entry> set = map.entrySet();
Map.Entry[] entries = set.toArray(new Map.Entry[set.size()]);
Arrays.sort(entries, new Comparator() {
public int compare(Object o1, Object o2) {
// 假設 Value 可轉為 Long 比較
Long v1 = Long.valueOf(((Map.Entry) o1).getValue().toString());
Long v2 = Long.valueOf(((Map.Entry) o2).getValue().toString());
return v1.compareTo(v2); // 升冪
}
});
return entries;
}
}
@SuppressWarnings("unchecked")
public static Map.Entry[] sortByKey(Map map) {
Set<Map.Entry> set = map.entrySet();
Map.Entry[] entries = set.toArray(new Map.Entry[set.size()]);
Arrays.sort(entries, new Comparator() {
public int compare(Object o1, Object o2) {
Comparable k1 = (Comparable) ((Map.Entry) o1).getKey();
Comparable k2 = (Comparable) ((Map.Entry) o2).getKey();
return k1.compareTo(k2);
}
});
return entries;
}
Map<String, Long> scores = new HashMap<>();
scores.put("Alice", 85L);
scores.put("Bob", 92L);
scores.put("Cindy", 78L);
Map.Entry[] sorted = MapSortUtils.sortByValueAsc(scores);
for (Map.Entry e : sorted) {
System.out.println(e.getKey() + " = " + e.getValue());
}
// 輸出:
// Cindy = 78
// Alice = 85
// Bob = 92
List<Map.Entry<String, Long>> list = scores.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toList());
專案若已升級 Java 8,建議改用 Stream API,程式碼更簡潔且型別安全。
Long,實際專案請依業務型別調整(Integer、Double、自訂 Comparable 等)。Map.Entry[] 而非 List,是為相容舊版 Java;新專案建議回傳 List<Map.Entry<K,V>>。LinkedHashMap。