对List中每个对象元素按时间顺序进行排序

参考链接:https://blog.csdn.net/wangjie1616/article/details/70196683

List> list = new ArrayList<>();
LinkedHashMap map = new LinkedHashMap<>();
System.out.println(localToUTC("2019-02-02 12:01:01"));
map.put("__time",localToUTC("2019-02-02 12:01:01"));
map.put("deviceId","1210840000001_1_1210840000001");
map.put("Timestamp_Local","2019-02-25 12:58:52.112");
map.put("Optional_Hydac_pressure_transducer_CAN_OK",1);
list.add(map);
System.out.println(" map1:"+map);
System.out.println(" list1:"+list);
map = new LinkedHashMap<>();
map.put("__time",localToUTC("2018-03-03 12:01:01"));
map.put("deviceId","1210840000002_1_1210840000002");
map.put("Timestamp_Local","2019-02-25 12:58:52.112");
map.put("Optional_Hydac_pressure_transducer_CAN_OK",2);
System.out.println(" map2:"+map);
list.add(map);
System.out.println(" sort before:"+list);
ListSort(list);
System.out.println(" sort later:"+list);
private static void ListSort(List> list) {
    Collections.sort(list, new Comparator>() {
        @Override
        public int compare(LinkedHashMap map1, LinkedHashMap map2) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date dt1 = (Date) map1.get("__time");
                Date dt2 = (Date) map2.get("__time");
                if (dt1.getTime() > dt2.getTime()) {
                    return 1;
                } else if (dt1.getTime() < dt2.getTime()) {
                    return -1;
                } else {
                    return 0;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return 0;
        }
    });
}

你可能感兴趣的:(java篇)