[Hundreds of wins] -Sanchuang competition realizes that the time attributes of the objects in the list are sorted in ascending order according to the size of time

Hello everyone, I am a pig arched by cabbage.

Background: The comments of the article show it, the first reply is ranked first, and the later comment shows the
effect: Insert picture description herecode:

//对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;
			}
		});
	}

test:

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

	}
	
}

result:
Insert picture description here

Only need to change the parameters when using

Published 24 original articles · praised 4 · visits 2038

Guess you like

Origin blog.csdn.net/weixin_44226263/article/details/105208838
Recommended