Sortedmap
SortedMap¶
Imagine a phone directory that auto-arranges itself π You add entries in any order, but it calmly keeps everything sorted by key.
π§ What is SortedMap?¶
SortedMap belongs to the Java Collections Framework
```java id="0j2l1n"
SortedMapπ It is a **Map that stores key β value pairs in sorted order of keys**
---
## π Key Characteristics
* β Keys are **unique**
* β Keys are **automatically sorted**
* β No null keys (in `TreeMap`)
* β Values can be duplicated
* Sorting based on:
* Natural order (`Comparable`)
* OR custom `Comparator`
---
## ποΈ Implementation
### β TreeMap (Primary Implementation)





```java id="4g0q2x"
SortedMap<String, Integer> map = new TreeMap<>();
- Uses Red-Black Tree π³
- Time complexity β O(log n)
βοΈ Important Methods¶
πΉ Basic Map Methods¶
```java id="yq8x1k" map.put("B", 2); map.put("A", 1); map.put("C", 3);
---
### πΉ SortedMap Specific Methods
```java id="4k0rjx"
map.firstKey(); // smallest key
map.lastKey(); // largest key
map.headMap("C"); // keys < "C"
map.tailMap("B"); // keys >= "B"
map.subMap("A", "C"); // range [A, C)
π§ Example¶
```java id="q6v2mw"
SortedMap
map.put("Banana", 2); map.put("Apple", 1); map.put("Mango", 3);
System.out.println(map);
β Sorted by keys β No duplicate keys
π Custom Sorting Example¶
```java id="k2q0fz"
SortedMap
map.put("A", 1); map.put("C", 3); map.put("B", 2);
System.out.println(map);
βοΈ SortedMap vs Map¶
| Feature | SortedMap πΏ | Map |
|---|---|---|
| Order | Sorted (by key) | No guarantee |
| Duplicate keys | Not allowed | Not allowed |
| Extra methods | Yes | No |
π― Interview Nuggets¶
SortedMapis an interface-
Implemented by:
TreeMap-
Extended by:
-
NavigableMap - Keys must be Comparable or use Comparator
π§ Memory Trick¶
SortedMap = Map + Sorted Keys πΏπΊοΈ