码迷,mamicode.com
首页 > 编程语言 > 详细

对List中每个对象元素按时间顺序排序

时间:2019-05-14 12:53:09      阅读:329      评论:0      收藏:0      [点我收藏+]

标签:gns   override   simple   vat   ***   err   date   rac   erb   

import com.fengshun.patient.entity.PatMasterIndex;
import org.apache.poi.ss.usermodel.DateUtil;
import org.junit.Test;

import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import java.text.SimpleDateFormat;
import java.util.*;

public class PatMasterIndexUtil {
public static class UserBean {
private String id;
private Date birthday;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public Date getBirthday() {
return birthday;
}

public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}

public static void main(String[] args) {
List<UserBean> list = new ArrayList<UserBean>();
UserListGenerate(list);
System.out.println("********排序前*******");
for (UserBean user : list) {
System.out.println(user.getBirthday());
}
ListSort(list);
System.out.println("******排序后*****");
for (UserBean user : list) {
System.out.println(user.getBirthday());
}
}
private static void UserListGenerate(List<UserBean> list) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
Date dt1 = format.parse("1980-11-01");
Date dt2 = format.parse("1981-12-01");
UserBean user1 = new UserBean();
UserBean user2 = new UserBean();
UserBean user3 = new UserBean();
user1.setId("zhagnsan");
user1.setBirthday(dt1);
user2.setId("lisi");
user2.setBirthday(dt2);
user3.setId("wangwu");
list.add(user1);
list.add(user2);
list.add(user3);
}catch (Exception e) {
e.printStackTrace();
}




}

private static void ListSort(List<UserBean> list) {
Collections.sort(list, new Comparator<UserBean>() {
@Override
public int compare(UserBean o1, UserBean o2) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
Date dt1 = o1.getBirthday();
Date dt2 = o2.getBirthday();
if (dt1.getTime() > dt2.getTime()) {
return -1;
} else if (dt1.getTime() < dt2.getTime()) {
return 1;
} else {
return 0;
}
} catch (Exception e) {
return 1;
}

}
});
}
}

对List中每个对象元素按时间顺序排序

标签:gns   override   simple   vat   ***   err   date   rac   erb   

原文地址:https://www.cnblogs.com/418836844qqcom/p/10861331.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!