Java-排序-变量比较器 [英] Java - Sort - Variable comparator
问题描述
我正在尝试根据用户输入对对象列表进行排序.我该如何使sort方法实现一个变体比较器?
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?
示例:
List<S3ObjectSummary> objectSummaryList = getObjectSummaries();
objectSummaryList.sort(Comparator.comparing(S3ObjectSummary::getKey);
如何根据需要根据getKey/getModified/其他任意属性进行上述排序?
How can I make above sort based upon getKey / getModified / other arbitrary properties as required?
推荐答案
如果所有键"都将链接到getter方法,则可以在函数中使用键/getter的静态映射:
If all "keys" will be linked to getter methods, you can have a static mapping of key/getter that you use in a function:
注意:我们将不得不使用原始类型Comparable
,因为我们不能使用不同的Functions<S3ObjectSummary, Comparable<T>>
(即使所有吸气剂都将返回Comparable<X>
对象,X
也会有所不同)
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)));
这篇关于Java-排序-变量比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!