Sub topic 12
Hash map or ordered map: choosing for the workload
This chapter assumes you know Big-O notation, basic map and set use, and the operations of an ordered map (floor, ceiling, range views). The question here is practical: given a workload, which one do you pick?
What each one gives you
A hash map finds a key by hashing it. Lookup, insert and delete take O(1) expected time. It stores no useful order, so iteration order tells you nothing.
An ordered map keeps keys sorted, usually in a balanced tree. Lookup, insert and delete take O(log n). In return it supports first, last, floor, ceiling and range views, and it iterates in key order.
| Need | Hash map | Ordered map |
|---|---|---|
| Lookup by exact key | O(1) expected | O(log n) |
| Insert and delete | O(1) expected | O(log n) |
| Smallest or largest key | O(n) scan | O(log n) |
| Nearest key (floor, ceiling) | Not supported | O(log n) |
| Range scan of k keys | O(n) scan | O(log n + k) |
| Iterate in sorted order | O(n log n) after sorting | O(n) |
| Key requirement | Hash and equality | A consistent ordering |
A decision rule
Ask what questions you will put to the keys.
If every query names an exact key, use a hash map. If any query asks "the next key after this one" or "all keys between a and b", use an ordered map.
Worked comparison
Suppose you store request counts per user ID and only ever read one user's count. A hash map fits.
Now suppose you store counts per timestamp and need all counts from the last five minutes. With a hash map you scan every entry. With an ordered map you jump to the lower bound and walk forward.
import java.util.TreeMap;
TreeMap<Long, Integer> counts = new TreeMap<>();
counts.put(1000L, 3);
counts.put(1060L, 5);
counts.put(1120L, 2);
counts.put(1400L, 7);
long now = 1400L;
// keys from now - 300 (inclusive) to now (inclusive)
System.out.println(counts.subMap(now - 300, true, now, true));
// {1120=2, 1400=7}The cost is O(log n + k), where k is the number of results. A hash map would cost O(n) for the same query.
Other factors
- Constant factors. Hashing is often several times faster than tree traversal for exact lookups, because trees chase pointers across memory.
- Worst case. A hash map degrades if many keys collide. A balanced tree guarantees O(log n) always.
- Key requirements. A hash map needs consistent
hashCodeandequals. An ordered map needs a consistent comparator, and that comparator also decides which keys count as equal. - Memory. Trees store extra pointers per entry. Hash tables keep spare capacity to stay fast.
- Mixed workloads. If you need fast exact lookups and occasional sorted output, a hash map plus a one-time sort may beat an ordered map. If sorted queries are frequent, keep the ordered map.
Exercise
Exercise
A service stores sessions by session ID and only ever fetches a session by its exact ID. A second service stores events by timestamp and must return all events in a given time window. Which structure fits each?
Show answer
The session store fits a hash map, since it needs only exact-key lookup at O(1) expected cost. The event store fits an ordered map, since a time window is a range query that costs O(log n + k) there, against an O(n) scan in a hash map.
Exercise
Why can an ordered map treat two keys as the same element even when they are not equal under equals?
Show answer
An ordered map decides equality with its comparator. If the comparator returns 0 for two keys, such as "Apple" and "apple" under a case-insensitive comparator, they count as one key.