简体   繁体   English

Java-排序-变量比较器

[英]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? 如何使sort方法实现变体比较器?

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? 如何根据需要根据getKey / getModified /其他任意属性进行上述排序?

If all "keys" will be linked to getter methods, you can have a static mapping of key/getter that you use in a function: 如果所有“键”都将链接到getter方法,则可以在函数中使用键/ getter的静态映射:

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) 注意:我们将不得不使用原始类型Comparable因为我们不能使用不同的Functions<S3ObjectSummary, Comparable<T>> (即使所有吸气剂都将返回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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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