Skip to content

Commit f9e10e9

Browse files
committed
feat(comparator): implement custom Comparator for Integer sorting
What - Added `MyClass` implementing `Comparator<Integer>`. - Overrode `compare(Integer a, Integer b)` to define explicit ordering logic: - `return a - b;` → ascending order. - (Alternative: `return b - a;` → descending order). Why - Default natural ordering of `Integer` already supports ascending order, but implementing `Comparator`: - Provides flexibility to change ordering logic as needed. - Demonstrates how to override comparison behavior explicitly. - Useful when sorting complex objects or applying custom business rules. Logic 1. `Comparator<T>` is a functional interface requiring a single method: `compare(T o1, T o2)`. 2. In this implementation: - If result < 0 → `a` comes before `b`. - If result > 0 → `a` comes after `b`. - If result == 0 → elements are equal. 3. With `a - b`, sorting is in ascending order (smaller numbers first). 4. With `b - a`, sorting flips to descending order (larger numbers first). Key Takeaways ✔ `Comparator` enables custom sorting beyond natural order. ✔ Subtraction (`a - b`) works for simple numeric comparisons. ✔ For objects, you would extract fields (e.g., `a.id - b.id`). ✔ From Java 8+, `Comparator.comparing()` and `.reversed()` offer more readable alternatives. ✔ This class can now be passed to `Collections.sort(list, new MyClass())` or `list.sort(new MyClass())`. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 36949df commit f9e10e9

File tree

1 file changed

+8
-0
lines changed
  • Java 8 Crash Course/Lambda Expression/Comparator Using Lambda Expression/src

1 file changed

+8
-0
lines changed
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import java.util.Comparator;
2+
3+
public class MyClass implements Comparator<Integer> {
4+
@Override
5+
public int compare(Integer a, Integer b) {
6+
return a-b; //ascending order main sort hoar hai. and b-a = descending order.
7+
}
8+
}

0 commit comments

Comments
 (0)