Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a List of objects by multiple fields [duplicate]

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?

like image 247
sim Avatar asked Jul 27 '11 20:07

sim


1 Answers

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).

like image 173
Daniel DiPaolo Avatar answered Sep 24 '22 20:09

Daniel DiPaolo