TreeMap¶
TreeMap is what you reach for when your data needs to stand in a neat, sorted queue instead of lounging in random
order π³π
Under the hood, itβs a self-balancing tree that keeps keys in order as you insert them.
π TreeMap
- Stores keyβvalue pairs
- Keys are sorted automatically
- Backed by a Red-Black Tree
π§ Key Characteristics¶
- β No
nullkeys (throws exception) - β
Allows
nullvalues - π Maintains sorted order of keys
- β±οΈ Operations:
O(log n) - π Not synchronized
π¦ Basic Example¶
import java.util.*;
public class Demo {
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>();
map.put(3, "C");
map.put(1, "A");
map.put(2, "B");
System.out.println(map);
}
}
π― Output¶
π Automatically sorted by key βοΈ
π How Sorting Works¶
πΉ 1. Natural Ordering (Comparable)¶
π Strings sorted alphabetically
πΉ 2. Custom Ordering (Comparator)¶
π§ͺ Important Methods¶
map.firstKey(); // smallest key
map.
lastKey(); // largest key
map.
ceilingKey(2); // β₯ key
map.
floorKey(2); // β€ key
map.
higherKey(2); // >
map.
lowerKey(2); // <
π TreeMap vs HashMap¶
| Feature | TreeMap | HashMap |
|---|---|---|
| Order | Sorted | No order |
| Structure | Tree | Hash table |
| Time | O(log n) | O(1) avg |
| Null key | β No | β Yes |
β οΈ Important Interview Points¶
β 1. Uses compareTo() or Comparator¶
- NOT
equals()for ordering
β 2. If compare returns 0 β treated as duplicate¶
β 3. Custom Object Example¶
class Person implements Comparable<Person> {
int age;
public Person(int age) {
this.age = age;
}
@Override
public int compareTo(Person p) {
return Integer.compare(this.age, p.age);
}
}
π― Real Interview Answer¶
βTreeMap is a SortedMap implementation that stores key-value pairs in sorted order using a Red-Black tree. It provides O(log n) time complexity for operations and uses compareTo or Comparator for ordering instead of hashCode.β
π§ Mental Model¶
Think of TreeMap like a leaderboard π
Every entry finds its correct position instantly.
π When to Use¶
β When you need:
- Sorted data
- Range queries
- Nearest key lookups
β Avoid when:
- You only need fast lookup β use HashMap