> 文章列表 > 使用Comparator 对List<Map>格式不严格字段排序

使用Comparator 对List<Map>格式不严格字段排序

使用Comparator 对List<Map>格式不严格字段排序

public static void main( String[] args ){String col1 = "time";String col2 = "num";//双数据源的集合ArrayList<Map> lists = produceData(col1, col2);//对双数据源集合惊醒排序 这里2个字段的灵活配置升序降序SortBy2Cols(lists,col1,OrderType.DESC,col2,OrderType.ASC);System.out.println(lists);}//模拟双数据源没有处理直接合并的情况(其实先预处理保持数据格式一直最好)private static ArrayList<Map> produceData(String col1, String col2) {ArrayList<Map> lists = new ArrayList<>();for (int i = 1; i < 10; i++) {HashMap<String, Object> map = new HashMap<String, Object>();//TIMESTAMP: oracle.sql.TIMESTAMPmap.put(col1,new TIMESTAMP("2021-01-0"+i+" 10:10:00"));map.put(col2,"x"+i);lists.add(map);}for (int i = 1; i < 10; i++) {HashMap<String, Object> map = new HashMap<String, Object>();//Timestamp: java.sql.Timestampmap.put(col1,new Timestamp(new Date("2021/01/0"+i+" 10:10:00").getTime()));map.put(col2,"y"+i);lists.add(map);}return lists;}public  static enum OrderType{ASC,DESC;}public static void SortBy2Cols(List<Map> list, String col1, OrderType type1, String col2, OrderType type2){//一般大家更熟悉reversed(),但reversed()不能做成动态排序//而实际情况是排序方式是前端指定的(动态的)list.sort(Comparator.comparing((Map p)->{Object o = p.get(col1);try {return o instanceof TIMESTAMP?((TIMESTAMP)o).timestampValue():((Timestamp)o);} catch (SQLException e) {throw new RuntimeException(e);}}, type1.equals(OrderType.ASC) ? Comparator.naturalOrder() : Comparator.reverseOrder()).thenComparing((Map p)->(String)(p.get(col2)),type2.equals(OrderType.ASC)? Comparator.naturalOrder() : Comparator.reverseOrder()));System.out.println(list);}

  输出结果:

[{num=x9, time=2021-01-09 10:10:00.0},

{num=y9, time=2021-01-09 10:10:00.0},

{num=x8, time=2021-01-08 10:10:00.0},

{num=y8, time=2021-01-08 10:10:00.0},

{num=x7, time=2021-01-07 10:10:00.0},

{num=y7, time=2021-01-07 10:10:00.0},

{num=x6, time=2021-01-06 10:10:00.0},

{num=y6, time=2021-01-06 10:10:00.0},

{num=x5, time=2021-01-05 10:10:00.0},

{num=y5, time=2021-01-05 10:10:00.0},

{num=x4, time=2021-01-04 10:10:00.0},

{num=y4, time=2021-01-04 10:10:00.0},

{num=x3, time=2021-01-03 10:10:00.0},

{num=y3, time=2021-01-03 10:10:00.0},

{num=x2, time=2021-01-02 10:10:00.0},

{num=y2, time=2021-01-02 10:10:00.0},

{num=x1, time=2021-01-01 10:10:00.0},

{num=y1, time=2021-01-01 10:10:00.0}]