基礎類型List排序
List<Integer> list = Arrays.asList(3,1,5,8,6,10); log.info("未排序的list:{}",list); //升序 list.sort(Comparator.naturalOrder()); log.info("升序的list:{}",list); //降序 list.sort(Comparator.reverseOrder()); log.info("降序的list:{}",list);
結果:
對list中的某個屬性排序
Student student1 = new Student("張三",19,175); Student student2 = new Student("李四",18,165); Student student3 = new Student("王五",20,170); List<Student> studentList = Lists.newArrayList(); studentList.add(student1); studentList.add(student2); studentList.add(student3); log.info("未排序的list:{}",studentList); //對年齡降序排序 List<Student> orderAgeDescList = studentList.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList()); log.info("對年齡降序排序后:{}",orderAgeDescList); //對年齡升序排序 List<Student> orderAgeAscList = studentList.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList()); log.info("對年齡升序排序后:{}",orderAgeAscList); //對年齡降序排序,對身高升序排序 List<Student> orderAgeDescAndHeightAscList = studentList.stream().sorted(Comparator.comparing(Student::getAge).reversed().thenComparing(Student::getHeight)).collect(Collectors.toList()); log.info("對年齡降序排序,對身高升序排序后:{}",orderAgeDescAndHeightAscList);
結果:
注意:當有多個屬性排序時,先滿足前一個排序,再對后一個排序