Skip to content

Commit dd5ef5e

Browse files
committed
feat(collections): add TreeMap demo with natural vs custom key ordering
What - Added `Main2.java` in `Package2` to demonstrate `TreeMap` ordering behavior. - Showed: 1. Natural ordering (ascending by keys, default behavior). 2. Custom ordering (descending by keys using lambda comparator). - Printed maps to compare key ordering in both cases. Why - `TreeMap` is a sorted map that orders entries based on key ordering or a provided comparator. - Demonstrating both natural and custom comparators clarifies how map iteration order is controlled. - Useful in real-world scenarios where ordered dictionaries are required (e.g., leaderboards, priority mappings). Logic 1. Created a `TreeMap<Integer, String>` with no comparator: - Defaults to **natural ascending key order**. - Input: `{22=Z, 1=f, 13=y}` - Stored/iterated as: `{1=f, 13=y, 22=Z}`. 2. Created a second `TreeMap<Integer, String>` with custom comparator `(a, b) -> b - a`: - Orders keys in **descending order**. - Input: `{22=z, 1=f, 13=y}` - Stored/iterated as: `{22=z, 13=y, 1=f}`. 3. Printed both results to highlight ordering difference. Key Takeaways ✔ `TreeMap` maintains sorted keys by default (ascending order). ✔ Supplying a comparator changes the key ordering policy. ✔ `(a, b) -> b - a` reverses natural order into descending. ✔ Different comparators → different logical "views" of the same data. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent e59bec3 commit dd5ef5e

File tree

1 file changed

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

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package Package2;
2+
3+
import java.util.Map;
4+
import java.util.TreeMap;
5+
6+
public class Main2 {
7+
public static void main(String[] args) {
8+
// Natural ordering (ascending by key).
9+
Map<Integer, String> m = new TreeMap<>();
10+
m.put(22, "Z");
11+
m.put(1, "f");
12+
m.put(13, "y");
13+
System.out.println("Before Manual sorting (Natural Order): " + m);
14+
15+
// Custom comparator (descending by key).
16+
Map<Integer, String> mm = new TreeMap<>((a, b) -> b - a);
17+
mm.put(22, "z");
18+
mm.put(1, "f");
19+
mm.put(13, "y");
20+
System.out.println("After Manual sorting (Descending Order): " + mm);
21+
}
22+
}

0 commit comments

Comments
 (0)