我有一个具有三个属性的学生类(class):
private String name;
private String age;
private String classStudy;
并实现了 Collections Comparable
@Override
public int compareTo(Student o) {
if(name==null) return -100;
else if(age==null) return -50;
else if(classStudy==null) return -10;
else
return (name + age + classStudy).compareTo(o.getName() + o.getAge() + o.getClassStudy());
}
主要方法:
public static void main(String []args){
List<Student> lists = new ArrayList<Student>();
lists.add(new Student("Tung", "24", "Java"));
lists.add(new Student("Hong", "26", "Uava"));
lists.add(new Student("yoiy", "42", "jrva"));
lists.add(new Student("Tung", "22", "Aava"));
lists.add(new Student("Tung", null, "Aava"));
lists.add(new Student("Tyn", "22", "Aava"));
lists.add(new Student("Tungh", "22", "Aava"));
lists.add(new Student("aung", "39", "ora"));
lists.add(new Student(null, null, "Aava"));
lists.add(new Student("Rung", "17", "Kva"));
lists.add(new Student(null, null, null));
Collections.sort(lists);
for(Student listTemp : lists){
System.out.println("Name : " + listTemp.getName() + ", Age : " + listTemp.getAge()
+ ", Class : "+ listTemp.getClassStudy());
}
}
结果: https://lh6.googleusercontent.com/-IIGbZ4uThRk/Ute08Qt6UJI/AAAAAAAAAsg/ahqgAKgMSHc/w325-h219-no/Capture6.PNG 但我希望 null 值按第一个位置排序(按照名称 -> 年龄 -> 类(class)排序)。我怎样才能做到这一点?
最佳答案
此方法将使 null
值排序到列表顶部,并按姓名、年龄和最后的类(class)对列表进行排序。它使用一个小的辅助函数,因为比较函数非常频繁地重复自身。
@Override
public int compareTo(Student s) {
int c1 = this.compare(this.name, s.name);
if (c1 != 0) {
return c1;
} else {
int c2 = this.compare(this.age, s.age);
if (c2 != 0) {
return c2;
} else {
return this.compare(this.classStudy, s.classStudy);
}
}
}
public int compare(String s1, String s2) {
if (s1 == null && s2 == null) {
return 0;
} else if (s1 == null) {
return -1;
} else if (s2 == null) {
return 1;
} else {
return s1.compareTo(s2);
}
}
关于java - 使用java中的Collections.sort()对列表中具有空值的多个字段进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21159296/