Sobes.tech
Junior — Middle

What functionality does the TreeMap data structure implement?

sobes.tech AI

Answer from AI

TreeMap in Java implements a data structure that stores key-value pairs in sorted order by key. It is based on a red-black tree, which provides logarithmic time for access, insertion, and deletion of elements. The main functionalities of TreeMap:

  • Storing elements in sorted order by key (natural order or using a Comparator).
  • Fast search, insertion, and deletion of elements.
  • Support for navigation methods such as firstKey(), lastKey(), headMap(), tailMap(), subMap().

Example of usage:

TreeMap<Integer, String> map = new TreeMap<>();
map.put(3, "three");
map.put(1, "one");
map.put(2, "two");

for (Integer key : map.keySet()) {
    System.out.println(key + " -> " + map.get(key));
}
// Will output keys in order: 1, 2, 3
What functionality does the TreeMap data structure… - sobes.tech