package csdn;
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("张三", "2000-01-01 20:20:20"));
list.add(new Man("李四", "2001-01-01 20:20:20"));
list.add(new Man("王五", "2005-05-01 20:20:20"));
list.add(new Man("BBB", "2003-01-01 20:20: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);
}
}