List集合通过日期时间字段来排序集合内容
- Method方法引用
ListParam:这个是集合对象、Object是集合对象中的对象Entity
//通过时间排序
Collections.sort(ListParam, new Comparator<Object>() {
@Override
public int compare(Object date1, Objectdate2) {
try {
if (date1.getCreateTime().getTime() < date2.getCreateTime().getTime()) {
return 1;
} else if (date1.getCreateTime().getTime() > date2.getCreateTime().getTime()) {
return -1;
} else {
return 0;
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
});
Run运行示例:
- 创建测试类:TestPan99
@Data
public class TestPan99 {
private int id;
private String name;
private Date createTime;
public static void main(String[] args) throws Exception{
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
List<TestPan99> list = new ArrayList<>();
TestPan99 testPan = new TestPan99();
testPan.setCreateTime(simpleDateFormat.parse("2021-4-17 17:17:17"));
list.add(testPan);
TestPan99 testPan1 = new TestPan99();
testPan1.setCreateTime(simpleDateFormat.parse("2021-4-15 15:15:15"));
list.add(testPan1);
TestPan99 testPan2 = new TestPan99();
testPan2.setCreateTime(simpleDateFormat.parse("2021-4-16 16:16:16"));
list.add(testPan2);
Collections.sort(list, new Comparator<TestPan99>() {
@Override
public int compare(TestPan99 date1, TestPan99 date2) {
try {
if (date1.getCreateTime().getTime() < date2.getCreateTime().getTime()) {
return 1;
} else if (date1.getCreateTime().getTime() > date2.getCreateTime().getTime()) {
return -1;
} else {
return 0;
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
});
for (TestPan99 testPan3 : list) {
System.out.println(simpleDateFormat.format(testPan3.getCreateTime()));
}
}
}
运行出来效果