我的類結構類似于:
class FinalResponse {
Source source;
List<Target> targets;
}
class Response {
Source source;
Target target;
}
class Source {
Long sourceId;
String sourceName;
}
class Target {
Long targetId;
String targetName;
}
我有兩個不同的表Source和Target,加入它們后,我在查詢輸出中得到四列。我正在Response使用這四列的值構造物件。我在具有這 4 個屬性的 Response 物件中有資料sourceId, sourceName, targetId, targetName。我可以sourceId, sourceName在多行上有相同的但targetId, targetName總是不同的。
我將所有target物件分組到相同的串列中source。
List<FinalResponse> finalResponses = responses.stream()
.collect(Collectors.groupingBy(
Response::getSource,
LinkedHashmap::new,
Collectors.mapping(Response::getTarget, Collectors.toList())
)) // Map<Source, List<Target>> is built
.entrySet()
.stream() // Stream<Map.Entry<Source, List<Target>>>
.map(e -> new FinalResponse(e.getKey(), e.getValue()))
.collect(Collectors.toList());
但有時無法對來自資料庫的回應進行排序,即使它已排序并且我已經使用過,但LinkedHashmap::new我的最終輸出List<FinalResponse> finalResponses也未排序。我希望我的最終輸出按照 sourceId 進行排序,所以我做了:
finalResponses.sort(Comparator.comparing(finalResponse->finalResponse.getSource().getSourceId()));
它適用于非空值,但如果我source(sourceId=null,sourceName=null)有多行,那么我會得到NullPointerException. 根據Source物件的sourceId屬性對集合進行排序的最佳方法是什么?
uj5u.com熱心網友回復:
Comparator.nullsLast或Comparator.nullsFirst應用于處理null比較項中的可能值:
finalResponses.sort(Comparator.nullsLast(
Comparator.comparing(fr -> fr.getSource().getSourceId())
));
或者像這樣:
finalResponses.sort(Comparator.comparing(
fr -> fr.getSource().getSourceId(),
Comparator.nullsLast(Comparator.naturalOrder())
));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/394587.html
上一篇:使用喜歡的串列排序佇列
