Sort a list of students with a Comparator

Description: You have students (name and marks). Sort them by marks, highest first. When the marks are equal, sort by name.

Hint:

  • Use Comparator.comparingInt(...).reversed() and thenComparing(...).

Solution

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

record Student(String name, int marks) { }

public class Main {
    public static void main(String[] args) {
        List<Student> list = new ArrayList<>(List.of(
                new Student("Meera", 88), new Student("Aman", 95),
                new Student("Riya", 88), new Student("Karan", 70)));

        list.sort(Comparator.comparingInt(Student::marks).reversed()
                .thenComparing(Student::name));

        list.forEach(System.out::println);
    }
}
Output

Student[name=Aman, marks=95]
Student[name=Meera, marks=88]
Student[name=Riya, marks=88]
Student[name=Karan, marks=70]

How it works

  • comparingInt compares by the marks, and reversed() makes it descending.
  • thenComparing is used only when the first comparison says the values are equal.

Read Lambda Expressions.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.