TreeMap

A TreeMap is part of the Java Collections Framework and implements the NavigableMap interface, which means it is a type of map that stores data in a sorted order. It is a Red-Black tree-based implementation of the Map interface, ensuring that its entries are ordered based on their keys.

Features

  • Sorted Order: A TreeMap automatically sorts the keys in ascending order, using either the natural ordering of the keys or a custom comparator.
  • No Null Keys: Unlike HashMap, TreeMap does not allow null keys. However, it can contain null values.
  • Fast Lookup and Updates: Like other map types, TreeMap provides efficient lookup, insertion, and removal operations. The time complexity for these operations is O(log n) due to the underlying Red-Black tree structure.

Common Methods

  • put(K key, V value): Adds a key-value pair to the map. If the key already exists, it updates the value.
  • get(Object key): Retrieves the value associated with the specified key.
  • remove(Object key): Removes the key-value pair associated with the specified key.
  • size(): Returns the number of key-value pairs in the map.
  • firstKey(): Returns the first (lowest) key in the map.
  • lastKey(): Returns the last (highest) key in the map.
  • subMap(K fromKey, K toKey): Returns a view of the portion of the map whose keys range from fromKey to toKey.

Example

Use Cases

  • When you need a sorted map of key-value pairs.
  • For range queries (e.g., find all keys between 5 and 20).
  • In applications where you frequently use navigation methods like floorKey() or ceilingKey().
  • Ideal for database indexes or caching systems where sorted access is essential.