Java Comparator Interface (original) (raw)

Last Updated : 25 Nov, 2025

The Comparator interface in Java is used to define custom sorting logic for objects. It belongs to java.util package and allows sorting of objects of user-defined classes without modifying their source code. It is especially useful when:

**Note: A comparator object can compare two objects of the same type and determine their order.

**Syntax

class MyComparator implements Comparator {
public int compare(Type obj1, Type obj2) {
// comparison logic
}
}

Sort Collections by One Field(Roll Number)

Java `

import java.util.*;

// Define the Student class class Student{

int rollno;
String name;

Student(int rollno, String name){
    
    this.rollno = rollno;
    this.name = name;
}

@Override
public String toString(){
    
    return rollno + ": " + name;
}

}

// Helper class implementing Comparator interface class SortByRoll implements Comparator{

public int compare(Student a, Student b) {
    return a.rollno - b.rollno; // Ascending order
}

}

// Driver class public class GFG{

public static void main(String[] args){
    
    List<Student> students = new ArrayList<>();
    students.add(new Student(111, "Mayank"));
    students.add(new Student(131, "Anshul"));
    students.add(new Student(121, "Solanki"));
    students.add(new Student(101, "Aggarwal"));

    // Sort students by roll number
    Collections.sort(students, new SortByRoll());

    System.out.println("Sorted by Roll Number:");
    for (Student s : students) {
        System.out.println(s);
    }
}

}

`

Output

Sorted by Roll Number: 101: Aggarwal 111: Mayank 121: Solanki 131: Anshul

Explanation

To sort in descending order, simply reverse the subtraction:

return b.rollno - a.rollno;

Methods in Comparator Interface

How Collections.sort() Works with Comparator

The Collections.sort() method arranges the elements of a List based on the rules defined by a Comparator.

Syntax

public static void sort(List list, Comparator<? super T> c)

The method uses the compare() function of the given Comparator to decide the order of elements. The compare() method compares two elements and returns:

Sorting by Multiple Fields (Name, then Age)

Java `

import java.util.*;

// Define the Student class class Student{

String name;
Integer age;

Student(String name, Integer age) {
    this.name = name;
    this.age = age;
}

public String getName() {
    return name;
}

public Integer getAge() {
    return age;
}

@Override
public String toString() {
    return name + " : " + age;
}

}

// Comparator for multiple fields class StudentComparator implements Comparator{

public int compare(Student s1, Student s2) {
    int nameCompare = s1.getName().compareTo(s2.getName());
    int ageCompare = s1.getAge().compareTo(s2.getAge());
    return (nameCompare == 0) ? ageCompare : nameCompare;
}

}

public class GFG{

public static void main(String[] args) {
    List<Student> students = new ArrayList<>();
    students.add(new Student("Ajay", 27));
    students.add(new Student("Sneha", 23));
    students.add(new Student("Simran", 37));

    System.out.println("Original List:");
    for (Student s : students) {
        System.out.println(s);
    }

    // Sort by name, then by age
    Collections.sort(students, new StudentComparator());

    System.out.println("\nAfter Sorting:");
    for (Student s : students) {
        System.out.println(s);
    }
}

}

`

Output

Original List: Ajay : 27 Sneha : 23 Simran : 37

After Sorting: Ajay : 27 Simran : 37 Sneha : 23

Explanation

Alternative Method: Using Comparator with Lambda

Java 8 introduced a more simple way to write comparators using lambda expressions. We can use the method mentioned below for achieving same result:

students.sort(

Comparator.comparing(Student::getName)

.thenComparing(Student::getAge)

);

Java `

import java.util.*;

// Define the Student class class Student { String name; Integer age;

// Constructor
Student(String name, Integer age) {
    this.name = name;
    this.age = age;
}

public String getName() {
    return name;
}

public Integer getAge() {
    return age;
}

// Method to print student details
@Override
public String toString() {
    return name + " : " + age;
}

}

public class ComparatorHelperClassExample { public static void main(String[] args) { List students = new ArrayList<>();

    students.add(new Student("Ajay", 27));
    students.add(new Student("Sneha", 23));
    students.add(new Student("Simran", 37));

    // Original List
    System.out.println("Original List:");

    // Iterating List
    for (Student it : students) {
        System.out.println(it);
    }

    System.out.println();

    // Sort students by name, then by age
    students.sort(Comparator.comparing(Student::getName).thenComparing(Student::getAge));

    // Display message after sorting
    System.out.println("After Sorting:");

    // Iterating using enhanced for-loop after sorting ArrayList
    for (Student it : students) {
        System.out.println(it);
    }
}

}

`

Output

Original List: Ajay : 27 Sneha : 23 Simran : 37

After Sorting: Ajay : 27 Simran : 37 Sneha : 23

Explanation