Junior — Middle
What is your experience with the TreeMap data structure in projects?
sobes.tech AI
Answer from AI
TreeMap in Java is an implementation of the SortedMap interface that stores key-value pairs in sorted order by key, using a red-black tree.
In projects, I used TreeMap when I needed to store data with quick access by sorted keys, for example:
- To implement a cache with the ability to quickly find the nearest keys.
- To store schedules or timestamps where order is important.
Example of usage:
TreeMap<Integer, String> map = new TreeMap<>();
map.put(3, "three");
map.put(1, "one");
map.put(2, "two");
// Iterating over keys in sorted order
for (Integer key : map.keySet()) {
System.out.println(key + " -> " + map.get(key));
}