Junior — Middle
What are the advantages and disadvantages of the TreeMap data structure?
sobes.tech AI
Answer from AI
TreeMap is an implementation of the SortedMap interface based on a red-black tree, which stores key-value pairs in sorted order by key.
Advantages:
- Automatic sorting of keys in natural order or by a provided Comparator.
- Fast search, insertion, and deletion — operations are performed in O(log n).
- Supports navigation methods (e.g., firstKey(), lastKey(), subMap()).
Disadvantages:
- Higher operation cost compared to HashMap due to the need to maintain tree balance.
- Not suitable if element order is not important and maximum access speed is required.
Usage example:
TreeMap<Integer, String> map = new TreeMap<>();
map.put(3, "три");
map.put(1, "бір");
map.put(2, "екі");
// Keys will be sorted: 1, 2, 3
for (Integer key : map.keySet()) {
System.out.println(key + " = " + map.get(key));
}