1 背景
对一个对象list做排序,排序字段是对象的sortNum,排序前剔除掉sortNum为null的对象
定义待排序的bean
public class TestBean {
private Integer id;
private String name;
private Integer sortNum;
}
2 一个排序失败的CASE
list.stream().filter(testBean -> testBean != null && testBean.getSortNum() != null)
.collect(Collectors.toList()).sort(Comparator.comparing(TestBean::getSortNum));
3 正确的排序
排序成功:
List<TestBean> listNew = list.stream().filter(testBean -> testBean != null && testBean.getSortNum() != null)
.sorted(Comparator.comparing(TestBean::getSortNum)).collect(Collectors.toList());
总结下:
list.stream.filter.collect.sort 没排序,list.stream.filter.sorted.collect 排序了
当然如果不需要剔除sortNum为空的对象,可以直接:
list.sort(Comparator.comparing(TestBean::getSortNum));
当然这种排序一旦有sortNum为空的对象,就会抛出空指针异常。
如果确实要排序带有空值的对象、并不想把这些对象剔除、又不想有NPE怎么办呢?
1)正序,且空值排前面
list.sort(Comparator.comparing(TestBean::getSortNum, Comparator.nullsFirst(Comparator.naturalOrder())));
2)正序,且空值排后面
list.sort(Comparator.comparing(TestBean::getSortNum, Comparator.nullsLast(Comparator.naturalOrder())));
3)倒序,且空值排前面
list.sort(Comparator.comparing(TestBean::getSortNum, Comparator.nullsFirst(Comparator.reverseOrder())));
4)倒序,且空值排后面
list.sort(Comparator.comparing(TestBean::getSortNum, Comparator.nullsLast(Comparator.reverseOrder())));
5)多条件排序
//先配置再排序
Comparator<Person> ageComparator = (o1, o2)->o1.getName().compareTo(o2.getName());
persons.sort(ageComparator); //按上面配置的顺序取值
System.out.println("Name升序排序后:");
persons.forEach((person)->System.out.println(person));
System.out.println("Name降序排序后:");
persons.sort(ageComparator.reversed()); //按上面配置的顺序反向取值
persons.forEach((person)->System.out.println(person));
// 多条件排序第二个写法,先按Age排序,再根据name排序
persons.sort(Comparator.comparing(Person::getAge).thenComparing(Person::getName));
System.out.println("多条件排序后:");
persons.sort(ageComparator.reversed()); //按上面配置的顺序反向取值
persons.forEach((person)->System.out.println(person));
6)中文排序
Collections.sort(persons, (Persono1, Persono2) -> Collator.getInstance(Locale.CHINESE).compare(o1.getName(), o2.getName()));