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
Java ArrayList
Java HashMap
Java HashSet and LinkedList
Java Generics
Exercises & Assignments
Sort a list of students with a Comparator
Count the frequency of words with a HashMap
Remove duplicates from a list and keep the order
Interview Questions & Answers
What is the difference between an array and an ArrayList in Java?
How does HashMap work internally in Java?
What is the difference between HashMap, Hashtable and ConcurrentHashMap?
Why must you override both equals() and hashCode() in Java?
What is the difference between Comparable and Comparator in Java?
What is the difference between ArrayList and LinkedList in Java?
What is the difference between fail-fast and fail-safe iterators?