package com.zip3;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
public class Test {
public static class Man {
private String birthday;
private String name;
public Man() {
}
public Man(String name, String birthday) {
this.name = name;
this.birthday = birthday;
}
@Override
public String toString() {
return name + " " + birthday;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
}
public static void main(String[] args) {
List<Man> list = new ArrayList<Man>();
list.add(new Man("张三", "2009-01-01 20:20:20"));
list.add(new Man("李四", "2001-01-01 21:10:20"));
list.add(new Man("王五", "2005-05-01 12:20:20"));
list.add(new Man("1B", "2005-05-01 10:22:20"));
list.add(new Man("2BBB", "2003-02-01 22:25:20"));
list.add(new Man("3BBB", "2004-01-01 23:22:20"));
list.add(new Man("4BBB", "2003-05-01 01:22:20"));
list.add(new Man("5BBB", "2007-01-01 02:25:20"));
list.add(new Man("6BBB", "2008-01-01 08:28:20"));
list.add(new Man("7BBB", "2000-01-01 05:24:20"));
list.add(new Man("8BBB", "2001-04-01 07:26:20"));
list.add(new Man("9BBB", "2002-01-01 09:27:20"));
list.add(new Man("10BBB", "2003-07-01 11:29:20"));
list.add(new Man("11BBB", "2003-06-01 12:21:20"));
list.add(new Man("12BBB", "2003-11-01 19:22:20"));
list.add(new Man("13BBB", "2005-06-01 15:25:20"));
list.add(new Man("14BBB", "2008-08-01 18:22:20"));
// System.out.println("排序前:" + list);
Collections.sort(list, new Comparator<Man>() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private Date getBirthday(Man m) {
if (m == null || m.getBirthday() == null)
return null;
try {
return sdf.parse(m.getBirthday());
} catch (ParseException e) {
return null;
}
}
public int compare(Man o1, Man o2) {
Date d1 = getBirthday(o1);
Date d2 = getBirthday(o2);
if (d1 == null && d2 == null)
return 0;
if (d1 == null)
return -1;
if (d2 == null)
return 1;
return d1.compareTo(d2);
}
});
System.out.println("排序后:" + list);
}
}
java List根据时间排序
最新推荐文章于 2023-03-09 09:12:55 发布