Java Collections Sorting: Comparable vs Comparator

Day 4 – Sorting in Java Collections | Comparable vs Comparator | Custom Object Sorting (Backend Developer Learning Series) Today I deeply revised how sorting works in Java Collections — especially with custom objects, which is extremely important in backend development. 📌 Sorting in Collection Framework In Java, we use the Collections utility class (java.util.Collections) to perform sorting and other helper operations. 🔹 Common Methods: Collections.sort(list) → Ascending order Collections.sort(list, Collections.reverseOrder()) → Descending Collections.reverse(list) Collections.max(list) Collections.min(list) Collections.unmodifiableList(list) Collections.synchronizedList(list) 💡 Collections class provides static helper methods for collection operations. 🔥 Sorting Custom Objects In real backend applications, we don’t sort integers or strings only. We sort objects like: Employee Product Student Orders Transactions These objects contain multiple properties. To sort them, Java provides two approaches: 1️⃣ Comparable (Default Sorting Logic) Defined in java.lang package Contains one abstract method: public int compareTo(Object o); ✔ Used when: You want default sorting logic Only one type of sorting is needed ✔ Implemented inside the class itself Example: public class Employee implements Comparable<Employee> { public int compareTo(Employee e) { return this.id - e.id; // Ascending by id } } Then: Collections.sort(employeeList); 2️⃣ Comparator (Multiple Sorting Logic) Defined in java.util package Contains: public int compare(Object o1, Object o2); ✔ Used when: Multiple sorting logic required Don’t want to modify blueprint class Sorting based on different fields Example: Collections.sort(list, new SortByIdDesc()); Collections.sort(list, new SortByPriceAsc()); Collections.sort(list, new SortByNameAsc()); #Java #BackendDeveloper #Collections #Comparable #Comparator #SpringBoot #LearningInPublic #InterviewPreparation #SoftwareEngineering

  • graphical user interface, text, application, email

To view or add a comment, sign in

Explore content categories