Java TreeMap: Sorted Key-Value Storage & NavigableMap Operations

TreeMap is an implementation of the NavigableMap and SortedMap interfaces based on a Red-Black Binary Search Tree. Unlike HashMap which stores entries in random hash buckets, TreeMap maintains its keys in guaranteed ascending sorted order.

Code Example: TreeMap in Action

import java.util.TreeMap;

public class TreeMapDemo {
    public static void main(String[] args) {
        // Automatically sorted by alphabetical key order
        TreeMap<String, Double> productPrices = new TreeMap<>();

        productPrices.put("MacBook Pro", 1999.0);
        productPrices.put("AirPods Max", 549.0);
        productPrices.put("iPhone 15", 999.0);
        productPrices.put("iPad Air", 599.0);

        // Keys are sorted alphabetically:
        System.out.println("Sorted Products: " + productPrices);

        // Range Queries (NavigableMap methods):
        System.out.println("First Product: " + productPrices.firstKey()); // AirPods Max
        System.out.println("Last Product:  " + productPrices.lastKey());  // iPhone 15

        // Extracting headMap (keys strictly before "MacBook Pro")
        System.out.println("HeadMap: " + productPrices.headMap("MacBook Pro"));
    }
}

HashMap vs. LinkedHashMap vs. TreeMap

Feature HashMap LinkedHashMap TreeMap
Ordering No order guaranteed Insertion Order Sorted Key Order
Time Complexity O(1) Average O(1) Average O(log n) Guaranteed
Null Keys Allows 1 null key Allows 1 null key Null key forbidden (Throws NPE)
Underlying Structure Hash Table (Array + TreeBins) Hash Table + Doubly-linked list Red-Black Binary Search Tree

Next Step

Now let us explore Queues, PriorityQueue, and the high-speed ArrayDeque. Proceed to: Java Queue & Deque (ArrayDeque) →

Frequently Asked Questions (FAQ)

Q1. How does TreeMap store elements in Java?
TreeMap implements the NavigableMap interface, backed internally by a Red-Black self-balancing Binary Search Tree. Keys are ordered either according to their natural comparable ordering or a custom Comparator provided at creation.
Q2. What is the time complexity of operations in a TreeMap?
TreeMap guarantees O(log n) time complexity for get(), put(), remove(), and containsKey() operations.
Q3. Can TreeMap accept null keys in Java?
No! Inserting a null key into a TreeMap throws a NullPointerException because the tree must invoke key.compareTo() to position the node inside the binary tree.

Explore Related Java Tutorials

Accelerate your Java mastery by studying these tightly connected core tutorials:

Java HashMap →

O(1) unordered map alternative.

Java TreeSet →

Backed by TreeMap.

Queue & Deque →

Entering queue collections.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!