jdk1.8之前的做法
参考: http://blog.csdn.net/enable1234___/article/details/53224740
jdk1.8新特性的做法:
参考: http://blog.csdn.net/aitangyong/article/details/54880228
Student.java
public class Student { private Long id;
private String name;
private String age;
private Date birthday;
public Student() {
}
public Student(Long id, String name, String age) {
this.id = id;
this.name = name;
this.age = age;
}
public Student(String name, String age) {
this.name = name;
this.age = age;
}
public Student(String name, String age, Date birthday) {
this.name = name;
this.age = age;
this.birthday = birthday;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public String getBirthdayStr() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(birthday);
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", birthday=" + getBirthdayStr() + "]";
}
}
Listtest.java
public class ListTest { @Test public void test() { List<Student> stuList = new ArrayList<Student>(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); stuList.add(new Student("wang", "18", sdf.parse("2007/04/01"))); stuList.add(new Student("li", "19", sdf.parse("2007/05/01"))); stuList.add(new Student("liu", "20", sdf.parse("2006/04/01"))); stuList.add(new Student("xi", "15", sdf.parse("2007/04/01"))); stuList.add(new Student("li", "17", sdf.parse("2007/05/01"))); stuList.add(new Student("wang", "19", sdf.parse("2007/06/01"))); // age升序 Comparator<Student> byIdASC = Comparator.comparing(Student::getAge); // named不分区大小写降序 Comparator<Student> byNameDESC = Comparator.comparing(Student::getName, String.CASE_INSENSITIVE_ORDER) .reversed(); // birthday 降序 Comparator<Student> byBirthdayDESC = Comparator.comparing(Student::getBirthday).reversed(); // 联合排序 Comparator<Student> finalComparator = byIdASC.thenComparing(byNameDESC).thenComparing(byBirthdayDESC); List<Student> result = stuList.stream().sorted(finalComparator).collect(Collectors.toList()); print(result); // 输出结果: // Student [name=xi, age=15, birthday=2007-04-01] // Student [name=li, age=17, birthday=2007-05-01] // Student [name=wang, age=18, birthday=2007-04-01] // Student [name=wang, age=19, birthday=2007-06-01] // Student [name=li, age=19, birthday=2007-05-01] // Student [name=liu, age=20, birthday=2006-04-01] }}