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

I'd like to return a List<Student> which contains the students sorted in a descending order by their averages. I have to use lambda expression with the stream() method.

Example class:

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...
}
Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
sasieightynine
  • 434
  • 1
  • 5
  • 16

1 Answers1

2

The return statement can be as simple as:

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

Comparator.comparingInt(Student::getAverage) returns a comparator that compares student average fields (assuming getter), and reversed() reverses the natural order.

ernest_k
  • 44,416
  • 5
  • 53
  • 99