1. 程式人生 > >含有對象的List集合實現字母數字混合排序

含有對象的List集合實現字母數字混合排序

gets 以及 實現 基本 ride man substring new 混合

List<PageData>    varList =  [{BOMCode=10A, mantotal=4}, {BOMCode=10B, mantotal=1}, {BOMCode=11A, mantotal=1}, {BOMCode=11B, mantotal=1}, {BOMCode=12A, mantotal=1}, {BOMCode=1A, mantotal=9}, {BOMCode=2A, mantotal=168}, {BOMCode=2B, mantotal=57}, {BOMCode=3A, mantotal=440}, {BOMCode=3B, mantotal=363}, {BOMCode=4A, mantotal=317}, {BOMCode=4B, mantotal=612}, {BOMCode=5A, mantotal=175}, {BOMCode=5B, mantotal=188}, {BOMCode=6A, mantotal=99}, {BOMCode=6B, mantotal=132}, {BOMCode=7A, mantotal=48}, {BOMCode=7B, mantotal=58}, {BOMCode=8A, mantotal=22}, {BOMCode=8B, mantotal=10}, {BOMCode=9A, mantotal=7}, {BOMCode=9B, mantotal=3}]

現在要對集合對象裏面的BOMCode做排序,返回一個排序後的varList:

Collections.sort(varList, new Comparator<PageData>(){                
            /*  
             * int compare(PageData pd1, PageData pd2) 返回一個基本類型的整型,  
             * 返回負數表示:pd1 小於pd2,  
             * 返回0 表示:pd1和pd2相等,  
             * 返回正數表示:pd1大於pd2。  
             
*/ @Override public int compare(PageData pd1, PageData pd2) { int number1; int number2; int ascii1 = 0; int ascii2 = 0; String s1 = pd1.getString("BOMCode"); String s2 = pd2.getString("BOMCode");
// 獲取每個數字的最後一位,判斷是否為大寫字母(判斷其ASCII碼是否在65到90之間) if ((int) (s1.toCharArray()[s1.length() - 1]) >= 65 && (int) (s1.toCharArray()[s1.length() - 1]) <= 90) { number1 = Integer.parseInt(s1.substring(0, s1.length() - 1)); ascii1 = (int) (s1.toCharArray()[s1.length() - 1]); } else { number1 = Integer.parseInt(s1); } if ((int) (s2.toCharArray()[s2.length() - 1]) >= 65 && (int) (s2.toCharArray()[s2.length() - 1]) <= 90) { number2 = Integer.parseInt(s2.substring(0, s2.length() - 1)); ascii2 = (int) (s2.toCharArray()[s2.length() - 1]); } else { number2 = Integer.parseInt(s2); } // 從小到大排序 if (number1 > number2) { return 1; } else if (number1 == number2) {// 數值相等則判斷是否有字母以及字母的順序 // 如果兩個都有字母,則判斷順序 // 按ASCII碼從小到大排列(即從A到Z排列) if (ascii1 < ascii2) { return 1; } } return -1; } }); return varList;

最後返回的varList如下:

[{BOMCode=1A, mantotal=9}, {BOMCode=2B, mantotal=57}, {BOMCode=2A, mantotal=168}, {BOMCode=3B, mantotal=363}, {BOMCode=3A, mantotal=440}, {BOMCode=4B, mantotal=612}, {BOMCode=4A, mantotal=317}, {BOMCode=5B, mantotal=188}, {BOMCode=5A, mantotal=175}, {BOMCode=6B, mantotal=132}, {BOMCode=6A, mantotal=99}, {BOMCode=7B, mantotal=58}, {BOMCode=7A, mantotal=48}, {BOMCode=8B, mantotal=10}, {BOMCode=8A, mantotal=22}, {BOMCode=9B, mantotal=3}, {BOMCode=9A, mantotal=7}, {BOMCode=10B, mantotal=1}, {BOMCode=10A, mantotal=4}, {BOMCode=11B, mantotal=1}, {BOMCode=11A, mantotal=1}, {BOMCode=12A, mantotal=1}]

含有對象的List集合實現字母數字混合排序