Java使用stream()按元素属性排序列表

时间:2018-08-25 11:46:45

标签: java sorting lambda java-stream

public static List<Student> getStudents(List<Student> students) {
        return students.stream(). // rest of the code comes here.
}

我想返回一个List<Student>,其中包含按平均水平降序排列的学生。我必须通过stream()方法使用lambda表达式。

示例类:

public class Student {

    private String name;
    private int birthYear;
    private double average;

    public Student(String name, int birthYear, double average) {
        this.name = name;
        this.birthYear = birthYear;
        this.average = average;
    }
    ...getters and setters...
}

1 个答案:

答案 0 :(得分:2)

return语句可以很简单:

return students.stream()
        .sorted(Comparator.comparingDouble(Student::getAverage).reversed())
        .collect(Collectors.toList());

Comparator.comparingInt(Student::getAverage)返回一个比较器,该比较器比较学生的average字段(假设有吸气剂),而reversed()则颠倒自然顺序。