//对象类型stream排序
List<User> users = new ArrayList<User>(){
{
add(new User("a", "1983/12/24", 36));
add(new User("a", "1993/12/24", 26));
add(new User("a", "1973/12/24", 46));
add(new User("a", "1995/12/24", 24));
add(new User("a", "1981/12/24", 38));
add(new User("a", "1991/12/24", 28));
}
};
//升序
List<User> ascUsers = users.stream().sorted(Comparator.comparing(User :: getAge)).collect(Collectors.toList());
//降序
List<User> descUsers = users.stream().sorted(Comparator.comparing(User :: getAge).reversed()).collect(Collectors.toList());
用户类:必须继承Comparable接口,否则排序调用Comparator.comparing的时候会报错,这点很重要。
public class User implements Comparable<User> {
@NotNull
private String name;
@Format(value="YYYY-MM-DD", message = "字符串格式不正确")
private String birthday;
private int age;
public User(){
}
public User(String name, String birthday, int age){
this.name = name;
this.birthday = birthday;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String brithday) {
this.birthday = birthday;
}
/**
* 两个相同类型的对象,比较多属相是否相等的时候
* 可以通过重写equals方法来实现
* @param object
* @return
*/
@Override
public boolean equals(Object object) {
if (object instanceof User) {
return this.name.equals(((User) object).getName()) && this.age == ((User) object).getAge();
} else {
return false;
}
}
/**
* 重写 equals 就应当重写 hashcode
* 因为当两个对象hashcode 值相等,但是 equals 比较为 false,
* 那么在 HashMap 中会产生链表,影响查询性能
* @return
*/
@Override
public int hashCode() {
return this.name.hashCode() + age;
}
@Override
public int compareTo(User user) {
return name.compareTo(user.getName());
}
}