Hackforge Academy

Category: java

Comparable

Published on 18 Feb 2026

Explanation

Comparator is an interface in the java.util package used to define custom sorting logic for objects. It is used when you want multiple sorting strategies.

Code:

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

Explanation

Comparator is used to sort objects based on different fields such as name, salary, or age without modifying the original class.

Code:

Collections.sort(list, new NameComparator());

Explanation

Example of sorting Student objects by name using Comparator.

Code:


Explanation


Code:

import java.util.*;
class Student {
    int id;
    String name;
    Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
}
class NameComparator implements Comparator<Student> {
    public int compare(Student s1, Student s2) {
        return s1.name.compareTo(s2.name);
    }
}

Explanation

Comparator can also be implemented using lambda expressions in Java 8 and above.

Code:

Collections.sort(list, (s1, s2) -> s1.name.compareTo(s2.name));

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community