TreeMap is an implementation of the NavigableMap and SortedMap interfaces based on a Red-Black Binary Search Tree. Unlike HashMap which stores entries in random hash buckets, TreeMap maintains its keys in guaranteed ascending sorted order.
import java.util.TreeMap;
public class TreeMapDemo {
public static void main(String[] args) {
// Automatically sorted by alphabetical key order
TreeMap<String, Double> productPrices = new TreeMap<>();
productPrices.put("MacBook Pro", 1999.0);
productPrices.put("AirPods Max", 549.0);
productPrices.put("iPhone 15", 999.0);
productPrices.put("iPad Air", 599.0);
// Keys are sorted alphabetically:
System.out.println("Sorted Products: " + productPrices);
// Range Queries (NavigableMap methods):
System.out.println("First Product: " + productPrices.firstKey()); // AirPods Max
System.out.println("Last Product: " + productPrices.lastKey()); // iPhone 15
// Extracting headMap (keys strictly before "MacBook Pro")
System.out.println("HeadMap: " + productPrices.headMap("MacBook Pro"));
}
}
| Feature | HashMap |
LinkedHashMap |
TreeMap |
|---|---|---|---|
| Ordering | No order guaranteed | Insertion Order | Sorted Key Order |
| Time Complexity | O(1) Average | O(1) Average | O(log n) Guaranteed |
| Null Keys | Allows 1 null key | Allows 1 null key | Null key forbidden (Throws NPE) |
| Underlying Structure | Hash Table (Array + TreeBins) | Hash Table + Doubly-linked list | Red-Black Binary Search Tree |
Now let us explore Queues, PriorityQueue, and the high-speed ArrayDeque. Proceed to: Java Queue & Deque (ArrayDeque) →
Accelerate your Java mastery by studying these tightly connected core tutorials:
O(1) unordered map alternative.
Backed by TreeMap.
Sorting keys.
Entering queue collections.