JAVA版List排序,按字元或數字型別排序,支援正序倒序
阿新 • • 發佈:2019-01-01
/** * 數字校驗(正、負、小數) * @param s * @return */ public static boolean isNumeric(String s) { if (s != null && !"".equals(s.trim())) return s.matches("^-?\\d+(\\.\\d+)?$"); else return false; } /** * List排序 * @param resultList Map陣列 * @param orderColumn 排序列名 * @param isString 是否按字串排序,否則按數字排序 * @param isAsc 是否正序 * @throws Exception */ public static void listSort(List> resultList, final String orderColumn, final boolean isString, final boolean isAsc) throws Exception { // 返回的結果集 Collections.sort(resultList, new Comparator>() { public int compare(Map o1, Map o2) { String s1 = StringUtils.getString(o1.get(orderColumn)); String s2 = StringUtils.getString(o2.get(orderColumn)); if (isString) { return s1.compareTo(s2) * (isAsc ? 1 : -1); } else { if (s1.equals("")) return isAsc ? -1 : 1; if (s2.equals("")) return isAsc ? 1 : -1; if (!isNumeric(s1) && !isNumeric(s2)) return s1.compareTo(s2) * (isAsc ? 1 : -1); ; if (!isNumeric(s1)) return isAsc ? -1 : 1; if (!isNumeric(s2)) return isAsc ? 1 : -1; return new BigDecimal(s1).compareTo(new BigDecimal(s2)) * (isAsc ? 1 : -1); } } }); } public static void main(String[] args) throws Exception { List> list = new ArrayList>(); Map map1 = new HashMap(); Map map2 = new HashMap(); Map map3 = new HashMap(); Map map4 = new HashMap(); Map map5 = new HashMap(); map1.put("number", null); map2.put("number", "44a"); map3.put("number", -3); map4.put("number", "36c"); map5.put("number", 11.1234); list.add(map1); list.add(map2); list.add(map3); list.add(map4); list.add(map5); listSort(list, "number", false, false); System.out.println(list); }