I have a List of Java objects that I want to sort according to more than one field.
public class graduationCeremony {
String campus;
String faculty;
String building;
}
Is it possible to use a Comparator or the Comparable interface to sort the list according to multiple fields? All the examples I have seen sort according to only one field. In other words, one can sort by ‘campus’ OR ‘faculty’ OR ‘building’. I want to sort by ‘campus’, then ‘faculty’, then ‘building’ (as it exists in SQL: ORDER BY campus, faculty, building)
I think this question has been asked before, but I don’t understand the accepted answer. Can someone expand or illustrate this answer?
Your Comparator would look like this:
Basically it continues comparing each successive attribute of your class whenever the compared attributes so far are equal (
== 0).