java的排序类 Collections

场景:比如说有一个List<Student> 里面有许多学生 我们想让这些学生按照年龄的大小排序

我们可以用java自带的 java.util.Collections 工具类来实现  

Collections.sort(rootList, studentComparator);

public Comparator<Student> studentComparator = new Comparator<Student>() {
        public int compare(Student o1, Student o2) {
            return o1.getAge() - o2.getAge();     //从小到大
        }
};

解释一下:sort方法  第一个是需要排序的list    第二个是排序的规则    规则是自己自定义的   

多个字段排序,比如先排年龄,年龄相同再排姓名  


Collections.sort(rootList, studentComparator);

public Comparator<Student> studentComparator = new Comparator<Student>() {
        public int compare(Student o1, Student o2) {
            int age=o1.getAge() - o2.getAge();
            if(age==0){
                return o1.getName() - o2.getName();
            }else{
                return age;
            }
        }
};
原文地址:https://www.cnblogs.com/coder-lzh/p/8673089.html