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 a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.