public static void main(String[] args) {
List<Map<String, String>> reslis = new ArrayList<Map<String, String>>();
Map<String,String> testMap1 = new HashMap<String,String>();
testMap1.put("name","zhangsan");
testMap1.put("age","23");
testMap1.put("address","beijing");
Map<String,String> testMap2 = new HashMap<String,String>();
testMap2.put("name","lisi");
testMap2.put("age","18");
testMap2.put("address","beijing");
Map<String,String> testMap3 = new HashMap<String,String>();
testMap3.put("name","wangwu");
testMap3.put("age","25");
testMap3.put("address","beijing");
Map<String,String> testMap4 = new HashMap<String,String>();
testMap4.put("name","zhaoliu");
testMap4.put("age","12");
testMap4.put("address","beijing");
reslis.add(testMap1);
reslis.add(testMap2);
reslis.add(testMap3);
reslis.add(testMap4);
System.out.println("排序前---------------------");
System.out.println(reslis);
System.out.println("排序后---------------------");
SortUtil.listSort(reslis,"age",true);
System.out.println(reslis);
}
结果展示![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/d16b2e892cb0ff4e5bf665a96ea9aa6e.png)
public class SortUtil {
private static final Comparator<Object> CHINA_COMPARE = Collator.getInstance(Locale.CHINA);
public static void listSort(List<Map<String,String>> list, String sortBy) {
LinkedHashMap<String, Boolean> sort = getSortBy(sortBy);
list.sort((m1, m2) -> {
int compare = 0;
for (Map.Entry<String, Boolean> entry : sort.entrySet()) {
String key = entry.getKey();
if (entry.getValue()) {
compare = compare(m2.get(key), m1.get(key), -1, 1);
} else
compare = compare(m1.get(key), m2.get(key), 1, -1);
if (compare != 0) {
return compare;
}
}
return compare;
});
}
public static void listSort(List<Map<String,String>> list, Object key, boolean isDesc) {
if (isDesc)
list.sort((m1, m2) -> compare(m2.get(key), m1.get(key), -1, 1));
else
list.sort((m1, m2) -> compare(m1.get(key), m2.get(key), 1, -1));
}
private static LinkedHashMap<String, Boolean> getSortBy(String sort) {
String pattern = "[^+-][a-zA-z_]+[+-]*";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(sort);
LinkedHashMap<String, Boolean> map = new LinkedHashMap<>();
while (m.find()) {
String group = m.group();
map.put(group.replace("+", "").replace("-", "").trim(), group.contains("-"));
}
return map;
}
private static int compare(Object o1, Object o2, int r1, int r2) {
if (o1 == null && o2 == null) {
return 1;
} else if (o2 == null) {
return r2;
} else if (o1 == null) {
return r1;
} else {
String s1 = o1.toString();
String s2 = o2.toString();
if (o1 instanceof Number && o2 instanceof Number) {
return new BigDecimal(s1).compareTo(new BigDecimal(s2));
}
return CHINA_COMPARE.compare(s1, s2);
}
}
}