1、实体类如下:
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
@Data
@NoArgsConstructor
public class Student {
private String name;
private Integer age;
private LocalDate date;
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
public Student(String name, Integer age, LocalDate date) {
this.name = name;
this.age = age;
this.date = date;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + ''' +
", age=" + age +
", date=" + date +
'}';
}
}
2、构造集合
public static List<Student> initData() {
List<Student> students =CollUtil.newArrayList();
students.add(new Student("1",21));
students.add(new Student("2",null));
students.add(new Student("3",null));
students.add(new Student("4",24));
students.add(new Student("5",null));
students.add(new Student("6",25));
students.add(new Student("7",null));
return students;
}
3、对于student 集合按照 年龄 age 进行排序
3.1 使用java8流进行排序
List<Student> students = initData();
students.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
System.out.println(students);
输出如下:提示空指针异常
4、解决属性为空时异常
4.1 传递排序规则,使 null 排在后面
// null 排在后面
students = students.stream().sorted(Comparator.comparing(Student::getAge, (a,b)->{
if (a == null) {
return (b == null) ? 0 : 1;
} else if (b == null) {
return -1;
} else {
return a - b ;
}
})).collect(Collectors.toList());
System.out.println(students);
4.2 使用 Comparator.nullsLast
// null 排在后面
students = students.stream().sorted(Comparator.comparing(Student::getAge,
Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());
System.out.println(students);
4.3 使用 Hutool CollUtil.sortByProperty
//默认空排在了前面
students = CollUtil.sortByProperty(students,"age");
System.out.println(students);
4.4 使用Hutool CompareUtil工具
CollUtil.sort(students,(s1,s2) -> CompareUtil.compare(s1.getAge(),s2.getAge(),false));
System.out.println(students);