Comparator.comparing(Department::getOrder)
原因:
public static <T, U extends Comparable<? super U>> Comparator<T> comparing(Function<? super T, ? extends U> keyExtractor)
{Objects.requireNonNull(keyExtractor);return (Comparator<T> & Serializable)(c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));
}
如果keyExtractor.apply(c1),那么keyExtractor.apply(c1).compareTo(XX)将报空指针异常
替代方案
Comparator.comparing(Department::getOrder, Comparator.nullsFirst(Comparator.naturalOrder()))
替代方案好处:
public static <T, U> Comparator<T> comparing(Function<? super T, ? extends U> keyExtractor,Comparator<? super U> keyComparator)
{Objects.requireNonNull(keyExtractor);Objects.requireNonNull(keyComparator);return (Comparator<T> & Serializable)(c1, c2) -> keyComparator.compare(keyExtractor.apply(c1),keyExtractor.apply(c2));
}
会先取出keyExtractor.apply(c1)和keyExtractor.apply(c2),放入比较器进行比较
而Comparator.nullsFirst作为比较器,会创建一个Comparators.NullComparator比较器
public static <T> Comparator<T> nullsFirst(Comparator<? super T> comparator) {return new Comparators.NullComparator<>(true, comparator);
}
Comparators.NullComparator比较器的compare接口实现中先进行空值判断处理,不为空的再进行代入比较器比较
/*** Null-friendly comparators*/
final static class NullComparator<T> implements Comparator<T>, Serializable {private static final long serialVersionUID = -7569533591570686392L;private final boolean nullFirst;// if null, non-null Ts are considered equalprivate final Comparator<T> real;@SuppressWarnings("unchecked")NullComparator(boolean nullFirst, Comparator<? super T> real) {this.nullFirst = nullFirst;this.real = (Comparator<T>) real;}@Overridepublic int compare(T a, T b) {if (a == null) {return (b == null) ? 0 : (nullFirst ? -1 : 1);} else if (b == null) {return nullFirst ? 1: -1;} else {return (real == null) ? 0 : real.compare(a, b);}}@Overridepublic Comparator<T> thenComparing(Comparator<? super T> other) {Objects.requireNonNull(other);return new NullComparator<>(nullFirst, real == null ? other : real.thenComparing(other));}@Overridepublic Comparator<T> reversed() {return new NullComparator<>(!nullFirst, real == null ? null : real.reversed());}
}