比如查询出来一批学生,先按照年龄从大到小排,年龄相同的按照名字从大到小(a~z)排,然后可以加其他的
学生实体类get/set忽略
public class Student {
private Integer id;
private String name;
private Integer age;
public Student(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
}
排序工具:
public class CompareTest implements Comparator<Student>{
Collator collator= Collator.getInstance(java.util.Locale.CHINA);
public static void main(String[] args) {
ArrayList<Student> list=new ArrayList<>();
list.add(new Student(3,"从",12));
list.add(new Student(1,"啊",9));
list.add(new Student(5,"饿",9));
list.add(new Student(2,"别",17));
list.add(new Student(4,"的",10));
Collections.sort(list,new CompareTest());
System.out.println(list.toString());
}
@Override
public int compare(Student o1, Student o2) {
int temp = o2.getAge().compareTo(o1.getAge());
if(temp==0){
temp = collator.compare(o1.getName(),o2.getName());
}
if(temp>0){
return 1;
}
if(temp<0){
return -1;
}
return 0;
}