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();
}
}
java的List四种排序实现方法
最新推荐文章于 2024-03-04 21:48:59 发布
本文详细介绍了如何使用Java对List<Student>类型的对象进行排序,包括使用Comparator接口、自定义比较规则、实现Comparable接口以及使用Collections.sort。通过实例展示了不同方法的实现和应用场景。
199

被折叠的 条评论
为什么被折叠?



