Java Notes
Learn Java TreeMap — sorted map by natural key order or custom comparator, NavigableMap methods for range queries, and when to choose TreeMap over HashMap.
TreeMap stores key-value pairs sorted by key. By default it uses the natural ordering of keys (alphabetical for Strings, numeric for numbers). You can also supply a custom Comparator to define any order.
Operations like get, put, remove are O(log n) — slower than HashMap's O(1), but you get sorted keys and powerful range-query methods in return.
Basic Usage — Automatic Sort
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Line by line:
- TreeMap maintains keys sorted at all times — even after additions.
firstKey()/lastKey()— smallest and largest key in O(log n).headMap("Priya")— all entries with key strictly less than "Priya".tailMap("Priya")— all entries with key ≥ "Priya".subMap("Asha", "Ravi")— keys from "Asha" (inclusive) to "Ravi" (exclusive).
Navigable Methods
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
These range-navigation methods are unique to TreeMap — HashMap does not have them.
Custom Order with Comparator
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
TreeMap Does Not Allow null Keys
TreeMap<String, Integer> map = new TreeMap<>();
// map.put(null, 1); // NullPointerException — cannot compare nullTreeMap needs to compare keys for ordering. null cannot be compared → NPE.
When to Choose TreeMap
Use TreeMap when:
- You need keys in sorted order
- You need range queries (all keys between X and Y)
- You need first/last key quickly
Use HashMap when:
- You only need lookup by key (faster, O(1))
- Order does not matter
Practice Task
Task: Create a TreeMap<String, Integer> storing city population (in lakhs): Mumbai: 200, Delhi: 190, Bangalore: 130, Chennai: 100, Hyderabad: 100. Print all cities alphabetically, the first and last alphabetically, and all cities whose name starts before "D" (headMap).
Solution:
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
What to observe: Keys print in alphabetical order regardless of insertion order. headMap("D") returns only "Bangalore" and "Chennai" since both come before "D" alphabetically. Try tailMap("H") — it returns cities from "H" onwards.
Continue the lesson path