场景一:普通排序
正序(升序)
list = list.stream().sorted().collect(Collectors.toList());
list = list.stream().sorted(Comparator.comparing(Student::getAge))
倒序(降序)
list = list.stream().sorted(Comparator.reverseOrder())
list = list.stream().sorted(Comparator.comparing(Student::getAge).reversed())
场景二:含空值排序
含空值的正序(升序)排序(按创建时间排序)
list = list.stream().sorted(Comparator.comparing(stu -> stu.getCreateTime(), Comparator.nullsFirst(Date::compareTo))).collect(Collectors.toList());
场景三:不用Stream
// 正序
list = list.sort(Comparator.comparing(Integer::intValue));
list = list.sort(Comparator.comparing(Student::getAge));
// 倒序
list = list.sort(Comparator.comparing(Integer::intValue).reversed());
list = list.sort(Comparator.comparing(Student::getAge).reversed());
List<String> list = Arrays.asList("banana", null, "apple", "cherry", null, "date");
// 使用nullsFirst,将null值排在非null值前面
List<String> sortedListNullsFirst = list.stream()
.sorted(Comparator.nullsFirst(Comparator.naturalOrder()))
.collect(Collectors.toList());
// 使用nullsLast,将null值排在非null值后面
List<String> sortedListNullsLast = list.stream()
.sorted(Comparator.nullsLast(Comparator.naturalOrder()))
.collect(Collectors.toList());
// 打印排序结果
sortedListNullsFirst.forEach(System.out::println);
sortedListNullsLast.forEach(System.out::println);
`
参考:
https://www.w3cschool.cn/java/codetag-stream-stream_sort.html