I\'m trying to sort a list of Objects based upon user input. How can I go about having the sort method implement a variant comparator?
Example:
List<
This will helps you:
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);
}
}));
If all "keys" will be linked to getter methods, you can have a static mapping of key/getter that you use in a function:
Note: we'll have to use raw type Comparable
as we can't use different Functions<S3ObjectSummary, Comparable<T>>
(even if all getters will return Comparable<X>
objects, X
will vary)
Map<String, Function<S3ObjectSummary, Comparable>> map = new HashMap<>();
map.put("key", s3 -> s3.getKey());
map.put("modified", s3 -> s3.getModified());
// other entries
Then sort using:
objectSummaryList.sort(Comparator.comparing(map.get(compareByKey)));