Q) How to sort collection on multiple attributes?
A) For classes that don’t implement
comparable interface, or when one needs even more control over ordering based on multiple attributes, a
Comparator interface should be used.
Example:
public class graduationCeremony {
String campus;
String faculty;
String building;
}
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;
}
}