JAVA List<Map<String, Object>> sort 多个排序写法
基本方法
/** * 排序= * * @param list * @param sort_key * @return */ public static List<Map<String, Object>> sort(List<Map<String, Object>> list, String sort_key,Boolean asc, String sort_key2,Boolean asc2) { Collections.sort(list, (map1, map2) -> { Double totalprice1 = map1 == null ? 0.0 : Double.parseDouble(map1.get(sort_key).toString()); Double totalprice2 = map2 == null ? 0.0 : Double.parseDouble(map2.get(sort_key).toString()); int i =0; i=asc?totalprice1.compareTo(totalprice2):totalprice2.compareTo(totalprice1); if (i != 0) return i; Double d1 = Double.parseDouble(map1.get(sort_key2).toString()); Double d2 = Double.parseDouble(map2.get(sort_key2).toString()); return asc2?d1.compareTo(d2):d2.compareTo(d1); }); return list; }
写个demo测试一下
static void testSort() { List<Map<String, Object>> list = new ArrayList<>(); Map<String, Object> item0 = new HashMap<>(); item0.put("price", 50); item0.put("tax", 3); item0.put("name", "item0"); Map<String, Object> item1 = new HashMap<>(); item1.put("price", 100.0); item1.put("tax", 1); item1.put("name", "item1"); Map<String, Object> item2 = new HashMap<>(); item2.put("price", 50.0); item2.put("tax", 1); item2.put("name", "item2"); Map<String, Object> item3 = new HashMap<>(); item3.put("price", 150.0); item3.put("tax", 3); item3.put("name", "item3"); list.add(item0); list.add(item1); list.add(item2); list.add(item3); List<Map<String, Object>> result = sort(list, "tax",true,"price",true); System.out.println(result); List<Map<String, Object>> result2 = sort(list, "price",true,"tax",true); System.out.println(result2); }
打印结果
[{price=50.0, name=item2, tax=1}, {price=100.0, name=item1, tax=1}, {price=50, name=item0, tax=3}, {price=150.0, name=item3, tax=3}]
[{price=50.0, name=item2, tax=1}, {price=50, name=item0, tax=3}, {price=100.0, name=item1, tax=1}, {price=150.0, name=item3, tax=3}]
结果符合
又多了一项无用的技能