按多个字段对对象列表排序 [英] Sort a List of objects by multiple fields
问题描述
我有一个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 BY campus,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.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;
}
}
基本上它会继续比较你的类的每个连续属性到目前为止,比较的属性是相等的( == 0
)。
Basically it continues comparing each successive attribute of your class whenever the compared attributes so far are equal (== 0
).
这篇关于按多个字段对对象列表排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!