问题描述
是否有内置的可能性在Java 8中创建一个空安全的映射比较器而无需编写 Comparator
的自己的实现?
Is there a build-in possibility to create a null-safe mapping comparator in Java 8 without writing a own implementation of Comparator
?
运行以下代码时,它会导致NPE,因为
的参数
Comparator.comparing()
可能会返回 null
值:
When running the following code, it causes a NPE because the keyExtractor
argument of Comparator.comparing()
may return a null
value:
public class ToSort
{
private String sortBy;
public ToSort(String sortBy)
{
this.sortBy = sortBy;
}
public String getSortBy()
{
return sortBy;
}
public static void main(String[] args)
{
// mapping comparator
Comparator<ToSort> comp = Comparator.comparing(ToSort::getSortBy);
SortedSet<ToSort> set = new TreeSet<>(comp);
ToSort o1 = new ToSort("1");
ToSort o2 = new ToSort(null);
set.add(o1);
System.out.println(set.contains(o2)); //NPE because o2.getSortBy() == null
}
}
使用
Comparator<ToSort> comp = Comparator.nullsFirst(Comparator.comparing(ToSort::getSortBy));
不能仅作为 ToSort
对象 null
正确处理。
does not work either as only ToSort
objects that are null
are treaded properly.
我知道如何编写自己的 Comparator
实现,我只是在寻找一个更优雅的解决方案,比如
I know how to write my own Comparator
implementation, I`m just searching a more "elegant" solution like
Comparator.comparingNullsFirst(ToSort::getSortBy)
推荐答案
找到一个可能的解决方案:
Found a possible solution:
Comparator.comparing(ToSort::getSortBy,
Comparator.nullsFirst(Comparator.naturalOrder())
)
这篇关于null-safe mapping使用默认实现的Comparator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!