✅️Comparator Functional Interface in Java
✅️Comparator Functional Interface in Java
Tired of default sorting? Use Comparator to define your own rules 🔥
👉 java.util.Comparator
👉 Used for custom ordering of objects
💡 compare() method: Returns:
-1 → first comes before second
0 → equal
1 → first comes after second
📌 Example (Descending Order):
Collections.sort(list, (a, b) -> a > b ? -1 : (a < b ? 1 : 0));
🧠 Why use Comparator? ✔ Multiple sorting logic
✔ No need to modify original class
✔ Works great with Lambda
✔ Clean & flexible code
📊 Complexity: ⏱ Time: O(n log n)
💾 Space: O(1)
🎯 Pro Tip: Use Comparator.comparing() + .thenComparing() for cleaner code!
💬 One line takeaway:
Control sorting your way — without touching the class 💯
#Java #SpringBoot #Comparator #JavaDeveloper #Coding
Comments
Comments from the original post on Instagram
No comments yet
