Java Comparator Interface


Java's Comparator interface belongs to the java.util package. Custom sorting logic for objects which deviates from their natural order is established through this interface. Comparator requires external definition and provides support for multiple sorting criteria unlike Comparable which resides within the class itself.


Key Features

  • Defines custom or multiple sorting logic
  • This sorting mechanism functions to order classes that exist outside the main system.
  • Allows sorting by any field
  • Works with methods like Collections.sort() and List.sort()
  • Supports lambda expressions (Java 8+)

Interface Declaration

 public interface Comparator {
    int compare(T o1, T o2);
}

Return values:

  • 0 – if o1 is equal to o2
  • < 0 – if o1 is less than o2
  • > 0 – if o1 is greater than o2

Comparator comparator = new Comparator() {
    public int compare(Type o1, Type o2) {
        // sorting logic
    }
}; 

Example: Sorting Custom Objects

Step 1: Create a class

 class Student {
    int id;
    String name;

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

Step 2: Create Comparators

 cclass SortById implements Comparator {
    public int compare(Student a, Student b) {
        return a.id - b.id;
    }
}

Step 3: Sort using Comparator

import java.util.*;

public class ComparatorExample {
    public static void main(String[] args) {
        List list = new ArrayList<>();
        list.add(new Student(103, "Alice"));
        list.add(new Student(101, "Charlie"));
        list.add(new Student(102, "Bob"));

        System.out.println("Sort by ID:");
        Collections.sort(list, new SortById());
        for (Student s : list) {
            System.out.println(s.id + " - " + s.name);
        }

        System.out.println("\nSort by Name:");
        Collections.sort(list, new SortByName());
        for (Student s : list) {
            System.out.println(s.id + " - " + s.name);
        }
    }
}



Onlinetpoint is optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.