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}]
时间: 2024-10-20 21:18:40