java对List的优雅排序
1、准备排序的数据
List<Student> students = new ArrayList<>(); students.add(new Student(1,"z1",25)); students.add(new Student(12,"z2",26)); students.add(new Student(9,"z3",27)); students.add(new Student(4,"z4",28)); students.add(new Student(1,"z5",29));
2,java8之前对集合排序
//java8之前的排序 Collections.sort(students,new ComparatorChain<Student>(){ public int compare(Student s1, Student s2) { return s1.getIndex().compareTo(s2.getIndex()); } }); students.forEach(s->{ System.out.println(s.toString()); });
结果:
Student{index=1, name='z1', age=25} Student{index=1, name='z5', age=29} Student{index=4, name='z4', age=28} Student{index=9, name='z3', age=27} Student{index=12, name='z2', age=26
3,java8对集合优雅排序
(1)
studentList.sort((Student s1,Student s2)->s1.getIndex().compareTo(s2.getIndex())); studentList.forEach(s -> { System.out.println(s.toString()); });
(2)
Collections.sort(studentList, Comparator.comparing(Student::getIndex)); studentList.forEach(s -> { System.out.println(s.toString()); });