null-safe mapping使用默认实现的Comparator

时间:2022-05-13 11:50:13

Is there a build-in possibility to create a null-safe mapping comparator in Java 8 without writing a own implementation of Comparator?

是否有内置的可能性在Java 8中创建一个空安全的映射比较器而无需编写自己的Comparator实现?

When running the following code, it causes a NPE because the keyExtractor argument of Comparator.comparing() may return a null value:

运行以下代码时,它会导致NPE,因为Comparator.comparing()的keyExtractor参数可能返回null值:

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

    }
}

Exception in thread "main" java.lang.NullPointerException at java.util.Comparator.lambda$comparing$77a9974f$1(Comparator.java:469) at java.util.Comparator$$Lambda$2/1480010240.compare(Unknown Source) at java.util.Comparators$NullComparator.compare(Comparators.java:83) at java.util.TreeMap.getEntryUsingComparator(TreeMap.java:376) at java.util.TreeMap.getEntry(TreeMap.java:345) at java.util.TreeMap.containsKey(TreeMap.java:232) at java.util.TreeSet.contains(TreeSet.java:234) at test.ToSort.main(ToSort.java:48)

例外在线程 “主” 显示java.lang.NullPointerException在java.util.Comparator.lambda $在了java.util.Comparator $$ LAMBDA $ 2 / 1480010240.compare(未知来源)在比较$ 77a9974f $ 1(Comparator.java:469) java.util.Comparators $ NullComparator.compare(Comparators.java:83)在java.util.TreeMap.getEntryUsingComparator(TreeMap.java:376)在java.util.TreeMap.getEntry(TreeMap.java:345)在java.util中.TreeMap.containsKey(TreeMap.java:232)at java.util.TreeSet.contains(TreeSet.java:234)at test.ToSort.main(ToSort.java:48)

Using

运用

Comparator<ToSort> comp = Comparator.nullsFirst(Comparator.comparing(ToSort::getSortBy));

does not work either as only ToSort objects that are null are treaded properly.

不起作用,因为只有空的ToSort对象被正确处理。

I know how to write my own Comparator implementation, I`m just searching a more "elegant" solution like

我知道如何编写自己的Comparator实现,我只是在寻找更“优雅”的解决方案

Comparator.comparingNullsFirst(ToSort::getSortBy)

1 个解决方案

#1


67  

Found a possible solution:

找到可能的解决方案:

Comparator.comparing(ToSort::getSortBy, 
      Comparator.nullsFirst(Comparator.naturalOrder())
)

#1


67  

Found a possible solution:

找到可能的解决方案:

Comparator.comparing(ToSort::getSortBy, 
      Comparator.nullsFirst(Comparator.naturalOrder())
)