1 回答

TA貢獻(xiàn)1155條經(jīng)驗(yàn) 獲得超0個(gè)贊
問(wèn)題出在以下行(Comparator.
為清楚起見(jiàn),我刪除了):
Comparator<MyCustomValue> valueComparator = nullsLast(comparing(MyCustomValue::getValue));
Comparator
您所做的將處理類型的null
值MyCustomValue
。它不會(huì)處理由 .null
返回的 s getValue
。您必須使用 2 參數(shù)版本Comparator.comparing
并null
為值提供 -safe 比較器:
valueComparator = comparing(MyCustomValue::getValue, nullsLast(naturalOrder()));
以上將處理您實(shí)際想要排序的常見(jiàn)情況value
。當(dāng)我查看您的代碼時(shí),我認(rèn)為您的意思是只使用value
fornull
檢查,否則不想按它排序。如果是這種情況,您可以將nullsLast( (x,y) -> 0)
其用作 null 安全的第二個(gè)參數(shù),因?yàn)?code>comparing它會(huì)將所有字符串視為相等。您也可以使用valueComparator = comparing(mcv -> mcv.getValue() == null)
因?yàn)?code>true按false
自然順序排列,但這可能不太清楚。
如果您還想處理null
s of MyCustomValue
,則必須再次將其包裝nullsLast
起來(lái)。
添加回答
舉報(bào)