我有一个具有以下属性的对象:
MyObject {
int order;
Date date;
}
我有一个对象列表:
[
{1, 2010},
{9, 2011},
{9, 2020},
{2, 2001},
{1, 2001}
]
我想先按顺序排序(升序),然后按日期排序(降序),所以期望的输出是:
[
{1, 2010},
{1, 2001}
{2, 2001}
{9, 2011},
{9, 2020},
]
我发现以下代码如何在不同的时间按不同的参数对列表进行排序
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;
}
};
}
}
我的困惑/问题是:
public int compare(Person o1, Person o2) {
for (PersonComparator option : multipleOptions) {
int result = option.compare(o1, o2);
if (result != 0) {
return result;
}
}
return 0;
}
它说如果 (result != 0) then return result
这意味着如果我打电话喜欢 Collections.sort(list, decending(getComparator(NAME_SORT, ID_SORT)));
并且“名称”比较返回非零值,将不适用于“ ID_SORT”
它将如何工作?请解释上面的代码如何在我上面的示例中工作?
还是我完全忘记了要点?
上面的代码看起来像具有排序标准的顺序。
“名称”比较返回非零值,不适用于“ ID_SORT”比较
这是正确的行为;如果为零,则它们相等,因此继续下一个条件。否则请使用此。
但是,我可以建议另一种方法-利用库排序是稳定的这一事实,因此,如果您先按年份,然后按顺序应用排序,则可以得到按顺序排序的列表,如果顺序相同,则按日期排序。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句