使用Stream对集合进行排序

JDK 8 用Stream对集合排序

​在开发过程当中,大多数的排序场景,咱们均可以使用数据库的order by关键字就可以给数据进行排序,可是有些场景是须要得到数据后,须要经过某个对象的属性自定义排序,这个时候咱们就能够使用jdk 8 的stream进行排序。java

根据学生的成绩进行排序

一、对List集合排序
学生对象web

public class Student{
    private String name;
    private Integer score;
    private Integer age;
  
    public Student(String name, Integer age, Integer score){
        this.name = name;
        this.age = age;
        this.score = score;
    }
    //省略getter和setter
}

根据学生成绩进行排序数据库

public static void main(String[] args){
    List<Student> studentList = new ArrayList<>();
		Student xiaoming = new Student();
		studentList.add(new Student("小明",19,100));
		studentList.add(new Student("小红",20,80));
		studentList.add(new Student("小红",18,90));

		//根据分数升序排序
		/** *须要注意的是,原来的数组是没有变化的,须要从新将排序后的数据集合进行toList() */
		List<Student> sortedStudentASC = studentList.stream().sorted(Comparator.comparing(Student::getScore)).collet(Collectors.toList());

		//降序排序
		List<Student> sortedStudentDESC = studentList.stream().sorted(Comparator.comparing(Student::getScore).reserved()).collet(Collectors.toList());
		
		sortedStudentASC.forEach(item -> System.out.println("name=" + item.getName+" age="+ item.getAge() + " score=" + item.getScore()));
		sortedStudentDESC.forEach(item -> System.out.println("name=" + item.getName+" age="+ item.getAge() + " score=" + item.getScore()));

}

控制台输出:数组

升序排序:
name=小红 age=20 score=80
name=小李 age=18 score=90
name=小明 age=19 score=100
---------------------------
降序排序
name=小明 age=19 score=100
name=小李 age=18 score=90
name=小红 age=20 score=80