TreeMap ClassThe TreeMap class is an implementation of the Map interface that uses a tree structure (specifically, a Red-Black Tree) for storage.
The most important feature of a TreeMap is that it stores its entries in sorted order based on the keys.
TreeMapComparator.null Keys: TreeMap does not allow null keys, as it cannot compare null to other keys for sorting. It does, however, allow null values.get, put, and remove operations is O(log n), which is slower than HashMap's O(1).TreeMap implements the NavigableMap interface, which provides useful methods for finding entries relative to others in the sorted map (e.g., floorEntry(), ceilingEntry(), higherKey(), lowerKey()).TreeMap WorksWhen you add a key-value pair, the key is used to position the entry within the underlying tree structure. This comparison is done using either the key's compareTo() method (if the key's class implements Comparable) or a Comparator provided to the TreeMap's constructor.
This tree structure is always kept balanced, which guarantees the O(log n) performance for operations.
TreeMapTreeMap is the perfect choice when you need to map keys to values and:
If you don't need sorting, HashMap or LinkedHashMap will provide better performance.
TreeMap ExampleHere is an example demonstrating the sorting behavior of a TreeMap.
import java.util.TreeMap;public class Main { public static void main(String[] args) { // Create a TreeMap of Integers and Strings TreeMap<Integer, String> courses = new TreeMap<>(); // Add items courses.put(103, "Data Structures"); courses.put(101, "Intro to Programming"); courses.put(201, "Web Development"); // The entries are automatically sorted by key System.out.println("Sorted TreeMap: " + courses); // NavigableMap methods System.out.println("First entry: " + courses.firstEntry()); System.out.println("Last entry: " + courses.lastEntry()); System.out.println("Entry with key higher than 101: " + courses.higherEntry(101)); } }