A TreeMap works like a HashMap but keeps its keys in sorted order. When you iterate, keys come out from smallest to largest:
import java.util.TreeMap;
TreeMap<String, Integer> scores = new TreeMap<>();
scores.put("Carol", 88);
scores.put("Alice", 95);
scores.put("Bob", 72);
for (String name : scores.keySet()) {
System.out.println(name);
}
// Alice, Bob, Carol
The tradeoff is speed. TreeMap operations (get, put, remove) run in time instead of , with space for entries. Internally, it uses a red-black tree rather than a hash table.
Use TreeMap when you need sorted iteration or methods like .firstKey(), .lastKey(), or .subMap(). Stick with HashMap when order does not matter and speed is your priority.