java的List四种排序实现方法

public class TestSort  {

    public static void main(String[] args) {
        List<Student> studentList= Lists.newArrayList();
        //第一种调用自身排序
        studentList.sort(Comparator.comparingInt(Student::getAge));
        //第二种调用自身排序,自定义排序规则
        studentList.sort((o1, o2) -> {return o1.getAge()> o1.getAge() ? 1 :( o1.getAge()==o2.getAge() ?0:-1);});
        //第三种调用自身排序,传入实现Comparator接口的对象
        StudentComparator scr=new StudentComparator();
        studentList.sort(scr);
        //第四种:使用工具排序,student实现Comparable接口,重写compareTo接口
        java.util.Collections.sort(studentList);
    }
}
class StudentComparator implements Comparator<Student>{
    @Override
    public int compare(Student o1, Student o2) {
        return o1.getAge()- o2.getAge();
    }
}


@Data
public class Student  implements  Comparable<Student>{
    int age;
    @Override
    public int compareTo(Student o) {
        return this.getAge()-o.getAge();
    }
}

上一篇:【ACM】杭电ACM题一直WA求高手看看代码


下一篇:杭电dp题集,附链接还有解题报告!!!!!