I was looking around for a method to sort a list of objects based on just one of its multiple fields (and i ended up just asking the question myself) but in my research, I came across this answer:
https://stackoverflow.com/a/1421537/1549672
I’m fairly new to java and this may be why, but I don’t quite understand this last method:
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;
}
};
}
could someone please explain how it works…and what exactly it does?
Thanks!
getComparatormethod will return comparator that will compare twoPersonobjects based on comparators passed in its arguments. Each ofPersonComparators is designed to compare Person by one of Person class field, for examplePersonComparator.ID_SORTwill compare Person objects byid(0 < 1 < 2 < 3 < …)PersonComparator.NAME_SORTwill compare Person objects by name using natural (dictionary) order (“a” < “aa” < “ab” < “b”).If your Person class have more fields then you can add new comparator to enum
PersonComparator.Also order of PersonComparators passed to
getComparatormethod is important.For example, if you have Persons
and you will create comparator by
it will sort person first by their
ids and in case ids ware equal then it will sort them by their name(1,"Jack") (2,"Adam") (2,"Jack")Also comparator created by
will firs compare names and only if names are equal it will compare ids of Persons, so you will get persons sorted this way
(2,"Adam") (1,"Jack") (2,"Jack")