Senior
In what cases is TreeMap needed if it is slower than HashMap?
sobes.tech AI
Answer from AI
TreeMap is needed when ordered access to keys is important, not just fast search. Unlike HashMap, which does not guarantee order, TreeMap stores elements in sorted order by key.
Use cases for TreeMap:
- Quickly obtaining the minimum or maximum key.
- Iterating over keys in sorted order.
- Operations to find nearest keys (e.g., floorKey, ceilingKey).
Example:
TreeMap<Integer, String> map = new TreeMap<>();
map.put(3, "three");
map.put(1, "one");
map.put(2, "two");
System.out.println(map.firstKey()); // 1
System.out.println(map.lastKey()); // 3
for (Integer key : map.keySet()) {
System.out.println(key + " -> " + map.get(key));
}
Here, elements will be output in order 1, 2, 3.