我怎麼能改寫這個:的Java:重寫比較與λ - nullsafe
private Comparator<Domain> byRank;
...
byRank = new Comparator<Domain>() {
@Override
public int compare(Domain d1, Domain d2) {
float tmp1 = d1.getDomainRank() == null ? 0 : d1.getDomainRank();
float tmp2 = d2.getDomainRank() == null ? 0 : d2.getDomainRank();
return Float.compare(tmp1, tmp2);
}
};
入λ?
據check null value before sorting using lambda expression,我嘗試這樣做:
byRank = Comparator.nullsFirst(Comparator.comparing(Domain::getDomainRank));
然而,它失敗:
java.lang.NullPointerException: null
at java.util.Comparator.lambda$comparing$77a9974f$1(Comparator.java:469)
at java.util.Comparators$NullComparator.compare(Comparators.java:83)
at java.util.PriorityQueue.siftUpUsingComparator(PriorityQueue.java:669)
at java.util.PriorityQueue.siftUp(PriorityQueue.java:645)
at java.util.PriorityQueue.offer(PriorityQueue.java:344)
at java.util.PriorityQueue.add(PriorityQueue.java:321)
編輯:拉姆達失敗,即使我比較之前檢查null比較的對象:
Queue<Domain> topByRank = new PriorityQueue<>(TOP, byRank);
...
for (Domain domain : domains) {
if (domain == null) { // check here
continue;
}
topByRank.add(domain); // here it fails
}
對於我所看到的d1或d2應爲null – freedev
@freedev我檢查空對象(請參閱編輯)。非lambda版本的工作沒有失敗。它不會在d1.getDomainRank()或d2.getDomainRank()上失敗嗎? – Michal
Comparator.comparing正在拋出NPE。你必須打開電話。請參閱http://stackoverflow.com/a/28500970/982149 – Fildor