java中List集合日期排序(Collections.sort排序)
作者:互联网
java中List集合日期排序(Collections.sort排序)
1、集合中有日期字段想排序
private static void listSorts(List list) { Collections.sort(list, new Comparator() { SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Override public int compare(Object o1, Object o2) { try { Date dt1 = sf.parse(o1.toString()); Date dt2 = sf.parse(o1.toString()); 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; } }); }
测试:
public static void main(String[] args) { Object[] objs2 = {"2022-07-06 14:56:14"}; Object[] objs3 = {"2022-07-06 15:56:14"}; Object[] objs0 = {"2022-07-06 11:56:14"}; List lists=new ArrayList(); lists.add("2022-07-06 14:56:14"); lists.add("2022-07-06 15:56:14"); lists.add("2022-07-06 11:56:14"); for(int s=0;s<lists.size();s++){ System.out.println("==排序前"+lists.get(s).toString()); } listSorts(lists); for(int s=0;s<list.size();s++){ System.out.println("==排序前"+lists.get(s).toString()); } }
运行结果:
标签:sort,Object,java,14,56,2022,06,排序,07 来源: https://www.cnblogs.com/sjzxs/p/16450999.html