TreeMap Example in Java
intermediate· Collections · Map
Problem
A TreeMap keeps its entries sorted by key at all times, unlike a HashMap, whose iteration order isn't guaranteed.
Add several out-of-order entries to a TreeMap and show that iterating it always visits them in sorted key order.
Input
put(Banana, 2), put(Apple, 5), put(Cherry, 3)
Output
Apple: 5, Banana: 2, Cherry: 3
Java Program
Java
import java.util.Map;
import java.util.TreeMap;
public class TreeMapExample {
public static void main(String[] args) {
TreeMap<String, Integer> scores = new TreeMap<>();
scores.put("Banana", 2);
scores.put("Apple", 5);
scores.put("Cherry", 3);
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}Output
Apple: 5
Banana: 2
Cherry: 3
Core Logic
TreeMap keeps every key in sorted order internally as entries are added, so no separate sorting step is ever needed before printing.
How It Works
- 1
new TreeMap<String, Integer>()creates a map that maintains its keys in ascending natural order at all times. - 2
put("Banana", 2),put("Apple", 5), andput("Cherry", 3)insert entries in that arrival order, out of alphabetical order. - 3Internally, TreeMap is backed by a red-black tree, which keeps itself balanced and sorted by key as entries are inserted.
- 4Iterating with
entrySet()afterward visitsApple, thenBanana, thenCherry— sorted order, regardless of insertion order.
Even though
Banana was inserted first, the map still prints Apple before it, since TreeMap always iterates in key order rather than insertion order.💡
Key Point: A HashMap would have printed these same three entries in some unspecified order — TreeMap is the one that guarantees sorted-by-key iteration on its own, with no extra sorting step required afterward.
Complexity
Time Complexity: O(log n)Space Complexity: O(n)
Why: Each put() call costs O(log n) to keep the underlying red-black tree balanced and sorted, and the map holds up to n entries.
Key Concepts
TreeMapsorted keysRed-Black tree