Skip to content

Commit e4cdbee

Browse files
committed
feat(collections): implement list sorting in descending order using lambda comparator
What - Added `Main.java` under `Package` to demonstrate sorting a `List<Integer>` in **descending order**. - Showcased two equivalent approaches: 1. Using `Collections.sort(list, (a, b) -> b - a)` 2. Using `list.sort((a, b) -> b - a)` (preferred shorthand in Java 8+). - Printed the sorted list to verify output. Why - Demonstrates practical use of **lambda expressions** as custom comparators. - Highlights difference between traditional `Collections.sort()` and the newer `List.sort()` method. - Reinforces how lambdas improve readability by avoiding verbose `Comparator` implementations. Logic 1. A list of integers `[1,2,3,4,5,6,7]` is created. 2. To sort in descending order: - The comparator `(a, b) -> b - a` is passed. - If `b > a`, result > 0 → ensures larger numbers come before smaller ones. 3. Output confirms reversed order `[7,6,5,4,3,2,1]`. 4. Alternative approaches (commented out) illustrate flexibility: - Using `Collections.sort()` with lambda. - Using a separate comparator class (`MyClass`) if desired. Key Takeaways ✔ `List.sort()` is the modern, concise way to sort collections (Java 8+). ✔ Lambdas simplify comparator definitions (`(a, b) -> b - a`). ✔ Sorting logic is customizable without creating boilerplate comparator classes. ✔ Comparator result convention: negative → first < second, positive → first > second. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent d441b81 commit e4cdbee

File tree

1 file changed

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

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package Package;
2+
3+
import java.util.ArrayList;
4+
import java.util.Collection;
5+
import java.util.Collections;
6+
import java.util.List;
7+
8+
public class Main {
9+
public static void main(String[] args) {
10+
List<Integer> list = new ArrayList<>();
11+
12+
list.add(1);
13+
list.add(2);
14+
list.add(3);
15+
list.add(4);
16+
list.add(5);
17+
list.add(6);
18+
list.add(7);
19+
20+
// Sort in descending order using lambda.
21+
22+
// Collections.sort(list, (a, b) -> b - a);
23+
// Or
24+
list.sort((a, b) -> b - a);
25+
26+
//Collections.sort(list, new MyClass());
27+
System.out.println(list);
28+
}
29+
}

0 commit comments

Comments
 (0)