2 回答

TA貢獻1155條經驗 獲得超0個贊
如果所有“鍵”都將鏈接到 getter 方法,則您可以在函數中使用鍵/getter 的靜態映射:
注意:我們必須使用原始類型Comparable,因為我們不能使用不同的類型Functions<S3ObjectSummary, Comparable<T>>(即使所有 getter 都會返回Comparable<X>對象,X也會有所不同)
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貢獻1829條經驗 獲得超9個贊
這將幫助您:
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);
}
}));
添加回答
舉報