【百占百胜】-三创比赛实现list中对象的时间属性按照时间的大小升序排序

大家好,我是被白菜拱的猪。

背景: 文章的评论对其展示,先回复的排在第一位,后评论的后展示
效果:在这里插入图片描述代码:

//对List<Reply> 按照回帖时间进行升序排序
	public  void ListSort(List<Reply> list) {
		Collections.sort(list, new Comparator<Reply>() {
			@Override
			public int compare(Reply o1, Reply o2) {
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				try {
					Date dt1 = format.parse(o1.getReplyTime());
					Date dt2 = format.parse(o2.getReplyTime());
					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 class ListSortTest {
	public static void main(String[] args) {
		try {	
			Reply reply1=new Reply(new Date());
			Thread.sleep(1000);
			Reply reply2=new Reply(new Date());
			Thread.sleep(1000);
			Reply reply3=new Reply(new Date());
			Thread.sleep(1000);
			Reply reply4=new Reply(new Date());
			
			List<Reply> list=new LinkedList<>();
			list.add(reply4);
			list.add(reply2);
			list.add(reply3);
			list.add(reply1);
			
			System.out.println("排序前");
			for(Reply reply:list){
				System.out.println(reply.getReplyTime());
			}
			System.out.println("排序后");
			DateUtil du=new DateUtil();
			du.ListSort(list);
			for(Reply reply:list){
				System.out.println(reply.getReplyTime());
			}
			
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}
	
}

结果:
在这里插入图片描述

使用时只用更改参数即可

发布了24 篇原创文章 · 获赞 4 · 访问量 2038

猜你喜欢

转载自blog.csdn.net/weixin_44226263/article/details/105208838