使用lambda对list排序
public class Person {
private String name;
private String birthday;
private Integer age;
public void setName(String name){
this.name = name;
}
public void setBirthday(String birthday){
this.birthday = birthday;
}
public void setAge(Integer age){
this.age = age;
}
public String getName(){
return this.name;
}
public String getBirthday(){
return this.birthday;
}
public Integer getAge(){
return this.age;
}
@Override
public String toString() {
return "Person [name=" + name + ", birthday=" + birthday + ", age=" + age + "]";
}
}
List<Person> personList = new ArrayList();
Person person = new Person( );
person.setName("jkl");
person.setBirthday("2000-01-05");
person.setAge(21);
personList.add(person);
person = new Person( );
person.setName("theshy");
person.setBirthday("1999-01-05");
person.setAge(22);
personList.add(person);
person = new Person( );
person.setName("rookie");
person.setBirthday("2001-01-05");
person.setAge(20);
personList.add(person);
System.out.println("根据生日降序 (字符串)");
personList = personList.stream().sorted((p1,p2) -> p2.getBirthday().compareTo(p1.getBirthday())).collect(Collectors.toList());
personList.stream().forEach(System.out :: println);
System.out.println("根据年龄升序 (数字)");
personList = personList.stream().sorted((p1,p2) -> p1.getAge().compareTo(p2.getAge())).collect(Collectors.toList());
personList.stream().forEach(System.out :: println);