I have an object with following properties:
MyObject {
int order;
Date date;
}
I have a list of objects:
[
{1, 2010},
{9, 2011},
{9, 2020},
{2, 2001},
{1, 2001}
]
I want to first sort on order (ascending) and than Date (descending), so expected output:
[
{1, 2010},
{1, 2001}
{2, 2001}
{9, 2011},
{9, 2020},
]
I found following code How do I sort a list by different parameters at different timed
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;
}
};
}
}
My confusion/question is :
public int compare(Person o1, Person o2) {
for (PersonComparator option : multipleOptions) {
int result = option.compare(o1, o2);
if (result != 0) {
return result;
}
}
return 0;
}
It says if (result != 0) then return result
which means if I call like Collections.sort(list, decending(getComparator(NAME_SORT, ID_SORT)));
and "name" compare returns non-zero, it will not apply compare to "ID_SORT"
How would it work?? Please explain how will the code above will work for my example above?
Or am I completely missing the point?