首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

TreeMap 以 String 為 Key 時排序異常的解決方案

     編輯:程式設計綜合問答

現象

向 TreeMap<String, Integer> 插入鍵 "1"、"2"..."10"..."20" 後,遍歷順序為:{1=0, 10=0, 11=0, 2=0, 20=0...},並非預期的數值順序。

原因

TreeMap 默認按 Key 的自然順序排序。String 類型按字典序比較,故 "10" < "2"。

解決方案

方案一:改用 Integer 類型 Key(推薦)

Map<Integer, Integer> map = new TreeMap<>();
map.put(1, 0);
map.put(10, 0);
// 遍歷順序即為 1, 2, 3...10, 11...

方案二:自定義 Comparator

Map<String, Integer> map = new TreeMap<>((a, b) -> {
    try {
        return Integer.compare(Integer.parseInt(a), Integer.parseInt(b));
    } catch (NumberFormatException e) {
        return a.compareTo(b); // 非數字字符串回退字典序
    }
});

總結

若 Key 代表數值,優先使用數值類型;必須用字符串時,提供數值解析的 Comparator。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved