null-Sicheres mapping Komparator mit Standard-Implementierungen
Gibt es eine build-in-Möglichkeit zu schaffen, eine null-sichere Zuordnung Komparator in Java 8 ohne schreiben einer eigenen Implementierung Comparator
?
Beim ausführen der folgenden code, der es bewirkt, dass eine NPE weil die keyExtractor
argument Comparator.comparing()
möglicherweise ein null
Wert:
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
bei java.util.Komparator.lambda$Vergleich$77a9974f$1(Komparator.java:469)
bei java.util.Komparator$$Lambda - $2/1480010240.vergleichen(Quelle Unbekannt)
bei java.util.Komparatoren$NullComparator.vergleichen(Komparator.java:83)
bei java.util.TreeMap.getEntryUsingComparator(TreeMap.java:376)
bei java.util.TreeMap.getEntry(TreeMap.java:345)
bei java.util.TreeMap.containsKey(TreeMap.java:232)
bei java.util.TreeSet.enthält(TreeSet.java:234)
beim test.ToSort.main(ToSort.java:48)
Mit
Comparator<ToSort> comp = Comparator.nullsFirst(Comparator.comparing(ToSort::getSortBy));
funktioniert entweder nicht, nur als ToSort
Objekte null
sind profilierte richtig.
Ich weiß, wie das schreiben meiner eigenen Comparator
Umsetzung, ich bin gerade auf der Suche eine "elegante" Lösung wie
Comparator.comparingNullsFirst(ToSort::getSortBy)
Du musst angemeldet sein, um einen Kommentar abzugeben.
Eine mögliche Lösung gefunden: