我有一个 Java 对象列表,我想根据多个字段对其进行排序.
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; }是否可以使用 Comparator 或 Comparable 接口根据多个字段对列表进行排序?我见过的所有例子都只根据一个领域进行排序.换句话说,您可以按校园"或教师"或建筑"进行排序.我想按校园"排序,然后是教员",然后是建筑"(它存在于 SQL 中:ORDER BYcampus,faculty, 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.campuspareTo(o2.campus); if (value1 == 0) { int value2 = o1.facultypareTo(o2.faculty); if (value2 == 0) { return o1.buildingpareTo(o2.building); } else { return value2; } } return value1; } }基本上,只要到目前为止比较的属性相等(== 0),它就会继续比较类的每个连续属性.
Basically it continues comparing each successive attribute of your class whenever the compared attributes so far are equal (== 0).
更多推荐
按多个字段对对象列表进行排序
发布评论