如何使用 Java 对 List 中每个对象元素按时间顺序进行排序
Java 实现
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class TestListSort {
private static class UserBean {
private String id;
private String birthday;
public String getId() {
return id;
}
void setId(String id) {
this.id = id;
}
String getBirthday() {
return birthday;
}
void setBirthday(String birthday) {
this.birthday = birthday;
}
// 重写 toString() 方法
public String toString() {
return "id:" + id + ", birthday:" + birthday;
}
}
public static void main(String[] args) {
List<UserBean> list = new ArrayList<>();
UserListGenerate(list);
System.out.println("排序前:" + list);
ListSort(list);
System.out.println("排序后:" + list);
}
private static void UserListGenerate(List<UserBean> list) {
UserBean user1 = new UserBean();
UserBean user2 = new UserBean();
UserBean user3 = new UserBean();
user1.setId("zhagnsan");
user1.setBirthday("1980-11-01");
user2.setId("lisi");
user2.setBirthday("1981-12-01");
user3.setId("wangwu");
user3.setBirthday("1980-12-01");
list.add(user1);
list.add(user2);
list.add(user3);
}
private static void ListSort(List<UserBean> list) {
list.sort((o1, o2) -> {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
Date dt1 = format.parse(o1.getBirthday());
Date dt2 = format.parse(o2.getBirthday());
return Long.compare(dt1.getTime(), dt2.getTime());
} catch (Exception e) {
e.printStackTrace();
}
return 0;
});
}
}
运行结果
排序前:[id:zhagnsan, birthday:1980-11-01, id:lisi, birthday:1981-12-01, id:wangwu, birthday:1980-12-01]
排序后:[id:zhagnsan, birthday:1980-11-01, id:wangwu, birthday:1980-12-01, id:lisi, birthday:1981-12-01]
参考资料