如何在不同的时间按不同参数对列表进行排序 [英] How do I sort a list by different parameters at different timed
问题描述
我有一个名为 Person
的类,有多个属性,例如:
I have a class named Person
with multiple properties, for example:
public class Person {
private int id;
private String name, address;
// Many more properties.
}
很多人
-objects存储在 ArrayList< Person>
中。我想通过多个排序参数对此列表进行排序,并且不时会有所不同。例如,我可能有一次希望按 name
升序排序,然后按地址
降序排序,另一次只按 id
降序。
A lot of Person
-objects are stored in an ArrayList<Person>
. I want to sort this list by multiple sort parameters, and different from time to time. For instance I might one time want to sort by name
ascending and then address
descending, and another time just by id
descending.
我不想创建自己的排序方法(即我想使用 Collections.sort(personList,someComparator)
。实现这一目标的最优雅的解决方案是什么?
And I don't want to create my own sort methods (i.e., I want to use Collections.sort(personList, someComparator)
. What is the most elegant solution that achieves this?
推荐答案
我认为你的枚举方法基本上是合理的,但是switch语句确实需要更加面向对象的方法。考虑:
I think your enum approach is basically sound, but the switch statements really need a more object oriented approach. Consider:
enum PersonComparator implements Comparator<Person> {
ID_SORT {
public int compare(Person o1, Person o2) {
return Integer.valueOf(o1.getId()).compareTo(o2.getId());
}},
NAME_SORT {
public int compare(Person o1, Person o2) {
return o1.getFullName().compareTo(o2.getFullName());
}};
public static Comparator<Person> decending(final Comparator<Person> other) {
return new Comparator<Person>() {
public int compare(Person o1, Person o2) {
return -1 * other.compare(o1, o2);
}
};
}
public static Comparator<Person> getComparator(final PersonComparator... multipleOptions) {
return new Comparator<Person>() {
public int compare(Person o1, Person o2) {
for (PersonComparator option : multipleOptions) {
int result = option.compare(o1, o2);
if (result != 0) {
return result;
}
}
return 0;
}
};
}
}
使用示例(使用静态导入)。
An example of usage (with a static import).
public static void main(String[] args) {
List<Person> list = null;
Collections.sort(list, decending(getComparator(NAME_SORT, ID_SORT)));
}
这篇关于如何在不同的时间按不同参数对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!