java android中对list的时间进行排序

时间:2021-06-14 19:35:10
public class HahaTime {
    
    public static void main(String[] args) {
        
        /**
         * 原来的日期
         */

        List<String> list = new ArrayList<String>();
        list.add("2014-03-04 22:22:22");
        list.add("2014-4-04 22:22:22");
        list.add("2014-05-04 22:22:22");
        list.add("2014-03-04 21:22:22");
        list.add("2014-03-2 22:21:22");
        list.add("2014-03-04 8:22:20");
        list.add("2014-03-04 22:22:8");
        list.add("2014-03-04 22:22:01");
        list.add("2014-03-5 22:22:8");

        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        List<String> list2 = new ArrayList<String>();
        /**
         * 格式化原来的日期,转换为:xxxx-xx-xx xx:xx:xx这样的格式,
         */
        for (int i = 0; i < list.size(); i++) {
            Date string;
            try {
                /**
                 * 转成标准日期
                 */
                string = dateFormat.parse(list.get(i).toString());
                /**
                 * 格式化成自己设定类型
                 */
                String string2 = dateFormat.format(string);
                /**
                 * 重新放入list集合
                 */
                list2.add(string2);

            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
        Collections.sort(list2);
        System.out.println("排序后");
        for (int i = 0; i < list2.size(); i++) {
            System.out.println(list2.get(i));
        }
        // Log.i("排序之前的list片段", "========" + list.toString());

        // Collections.sort(list);
        // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

        // Log.i("排序后的情况,22222,", "=========" + list.toString());

    }

    public static class MapComparator implements
            Comparator<Map<String, Object>> {
        
        //@Override
        public int compare(Map<String, Object> o1, Map<String, Object> o2) {
            // TODO Auto-generated method stub
            Date b1 = (Date) o1.get("time");
            Date b2 = (Date) o2.get("time");
            if (b2 != null) {
                return b1.compareTo(b2);
            }
            return 0;
        }
    }

    
}