2 回答

TA貢獻(xiàn)1155條經(jīng)驗(yàn) 獲得超0個(gè)贊
如果所有“鍵”都將鏈接到 getter 方法,則您可以在函數(shù)中使用鍵/getter 的靜態(tài)映射:
注意:我們必須使用原始類型Comparable,因?yàn)槲覀儾荒苁褂貌煌念愋虵unctions<S3ObjectSummary, Comparable<T>>(即使所有 getter 都會(huì)返回Comparable<X>對(duì)象,X也會(huì)有所不同)
Map<String, Function<S3ObjectSummary, Comparable>> map = new HashMap<>();
map.put("key", s3 -> s3.getKey());
map.put("modified", s3 -> s3.getModified());
// other entries
然后使用排序:
objectSummaryList.sort(Comparator.comparing(map.get(compareByKey)));

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超9個(gè)贊
這將幫助您:
String sortBy = "key";
list.sort(Comparator.comparing(report -> {
try {
return (Comparable) report.getClass().getDeclaredField(sortBy).get(report);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("exception", e);
}
}));
添加回答
舉報(bào)