TreeMap in Java
TreeMap is a Map implementation backed by a red-black tree, a self-balancing binary search tree. The most important characteristic of TreeMap is that it al...
Sorted Keys with TreeMap
TreeMap is a Map implementation backed by a red-black tree, a self-balancing binary search tree. The most important characteristic of TreeMap is that it always keeps its keys in sorted order. By default, keys are sorted according to their natural ordering, which means they must implement Comparable. Alternatively, you can provide a custom Comparator at construction time to define a different sorting logic.
Because TreeMap maintains sorted order, it offers a range of navigation methods not available in HashMap or LinkedHashMap. These include firstKey(), lastKey(), headMap(toKey), tailMap(fromKey), floorKey(key), ceilingKey(key), and subMap(fromKey, toKey). These methods make TreeMap the best choice when you need sorted keys or range queries.
TreeMap<String, Integer> wordCount = new TreeMap<>(); wordCount.put("banana", 3); wordCount.put("apple", 5); wordCount.put("cherry", 2); System.out.println(wordCount.firstKey()); // apple System.out.println(wordCount.headMap("cherry")); // {apple=5, banana=3}
The time complexity for put(), get(), and remove() in TreeMap is O(log n) because of the tree structure, compared to O(1) average for HashMap. This trade-off is worthwhile when ordering or range access is required.
TreeMap does not allow null keys because it needs to compare keys for ordering. Inserting a null key throws a NullPointerException. Null values, however, are permitted.
TreeMap is also not thread-safe. For concurrent sorted access, use ConcurrentSkipListMap, which provides similar functionality with thread safety and similar O(log n) performance.
Interview tip: Interviewers sometimes ask when to prefer TreeMap over HashMap. The answer is whenever you need keys in sorted order, want to find the closest key to a given value, or need efficient range-based queries. Raw lookup speed alone still favors HashMap.