Sobes.tech
Middle+

What is the purpose of TreeMap?

sobes.tech AI

Answer from AI

TreeMap in Java is an implementation of the NavigableMap interface that stores key-value pairs in sorted order by keys.

Main features and purpose of TreeMap:

  • Keys are automatically sorted in natural order or using a Comparator.
  • Allows fast search, insertion, and deletion operations with logarithmic complexity.
  • Supports navigation methods, such as retrieving nearest keys, subranges.

Example of usage:

TreeMap<Integer, String> map = new TreeMap<>();
map.put(3, "Three");
map.put(1, "One");
map.put(2, "Two");

// Keys will be sorted: 1, 2, 3
for (Integer key : map.keySet()) {
    System.out.println(key + " -> " + map.get(key));
}

TreeMap is useful when you need a sorted collection with quick access by key and the ability to navigate through ranges.