简体   繁体   中英

Java - Sort - Variable comparator

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<S3ObjectSummary> objectSummaryList = getObjectSummaries();
objectSummaryList.sort(Comparator.comparing(S3ObjectSummary::getKey);

How can I make above sort based upon getKey / getModified / other arbitrary properties as required?

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)));

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);
    }
}));    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM