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();
}
}
标签:getAge,java,List,studentList,Student,排序,public,o1 来源: https://blog.csdn.net/sunyufeng22/article/details/120677277