我有一个具有三个属性的班级学生:
private String name;
private String age;
private String classStudy;
并实现可比较的集合
@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
值排序到列表顶部,并按名称,年龄和最后的班级学习对列表进行排序。 它使用一个小的帮助程序函数,因为比较函数非常频繁地重复自己。
@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);
}
}
像这样做
@Override
public int compareTo(Student o) {
if(name==null||o.getName()==null){
return 1;
}
if(!name.equalsIgnoreCase(o.getName())){
return name.compareToIgnoreCase(o.getName());
}
if(age==null||o.getAge()==null){
return 1;
}
if(!age.equalsIgnoreCase(o.getAge())){
return age.compareToIgnoreCase(o.getAge());
}
if(classStudy==null|| o.getClassStudy()==null){
return 1;
}
if(!classStudy.equalsIgnoreCase(o.getClassStudy())){
return classStudy.compareToIgnoreCase(o.getClassStudy());
}
return 0;
}