# List集合通过日期时间字段来排序集合内容

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()));
        }
    }
}

运行出来效果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值