问题描述:对象集合中,根据对象的某个属性进行升降排序时,未考虑对应属性的null值,导致出现空指针异常。
解决方法:Comparator.nullsFirst和Comparator.nullsLast
List<User> nList = list.stream().sorted(
Comparator.comparing(User::getCode, Comparator.nullsFirst(String::compareTo)))
.collect(Collectors.toList());
下见源码:
/**
* Returns a null-friendly comparator that considers {@code null} to be
* less than non-null. When both are {@code null}, they are considered
* equal. If both are non-null, the specified {@code Comparator} is used
* to determine the order. If the specified comparator is {@code null},
* then the returned comparator considers all non-null values to be equal.
*
* <p>The returned comparator is serializable if the specified comparator
* is serializable.
*
* @