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:
public class GraduationCeremonyComparator implements Comparator<GraduationCeremony> { public int compare(GraduationCeremony o1, GraduationCeremony o2) { int value1 = o1.campus.compareTo(o2.campus); if (value1 == 0) { int value2 = o1.faculty.compareTo(o2.faculty); if (value2 == 0) { return o1.building.compareTo(o2.building); } else { return value2; } } return value1; } }
Basically it continues comparing each successive attribute of your class whenever the compared attributes so far are equal (== 0
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With