Skip to content
C

TreeMap

TreeMap is an implementation of the Map interface that automatically keeps its key-value pairs sorted based on the keys, either in their natural order or a custom order you define.


1. What is TreeMap?

TreeMap is an implementation of the Map interface that automatically keeps its key-value pairs sorted based on the keys, either in their natural order or a custom order you define.

2. Why is it used?

It's useful whenever key-value data must always stay sorted by key — like maintaining a dictionary of words in alphabetical order, or numeric IDs in ascending order, without manual sorting.

3. Real-Life Example

Think of a well-organized dictionary where every word (key) and its meaning (value) is automatically kept in alphabetical order, regardless of the order in which words were originally added.

4. Syntax

java
TreeMap<KeyType, ValueType> mapName = new TreeMap<>();

5. Example Program

java
import java.util.TreeMap; public class TreeMapDemo { public static void main(String[] args) { TreeMap<String, Integer> ages = new TreeMap<>(); ages.put("Zara", 22); ages.put("Amit", 25); System.out.println(ages); } }

Output:

{Amit=25, Zara=22}

6. Key Points to Remember

  • TreeMap keeps its entries sorted by key automatically at all times.
  • It does not allow a null key, since sorting requires comparing keys.
  • TreeMap is generally slower than HashMap due to the overhead of maintaining sorted order.