Java TreeMap

A Java TreeMap stores key-value pairs with the keys kept in sorted order. It works like a map, but unlike HashMap, it gives predictable ordering by key.

TreeMap is part of java.util. It is useful when you need to look up values by key and also process the keys in alphabetical or numeric order.

Create A TreeMap

Import java.util.TreeMap, then choose the type for the keys and the type for the values. For example, TreeMap<String, Integer> stores string keys and integer values.

import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        TreeMap<String, Integer> scores = new TreeMap<>();

        scores.put("Mia", 95);
        scores.put("Noah", 88);
        scores.put("Ava", 91);

        System.out.println(scores);
        System.out.println("Ava: " + scores.get("Ava"));
        System.out.println("First key: " + scores.firstKey());
        System.out.println("Last key: " + scores.lastKey());
    }
}

Output:

{Ava=91, Mia=95, Noah=88}
Ava: 91
First key: Ava
Last key: Noah

The keys are printed as Ava, Mia, and Noah because strings are sorted alphabetically. The firstKey() and lastKey() methods are available because TreeMap is a sorted map.

Keys Must Be Unique

Like other maps, a TreeMap cannot store the same key twice. If you use put() with a key that already exists, the new value replaces the old value.

import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        TreeMap<Integer, String> seats = new TreeMap<>();

        seats.put(12, "Liam");
        seats.put(7, "Emma");
        seats.put(19, "Olivia");
        seats.put(7, "Sophia");

        System.out.println(seats);
        System.out.println("Seat 7: " + seats.get(7));
        System.out.println("Has seat 12: " + seats.containsKey(12));
    }
}

Output:

{7=Sophia, 12=Liam, 19=Olivia}
Seat 7: Sophia
Has seat 12: true

The second value for key 7 replaces Emma with Sophia. The map still has only three entries, and the numeric keys stay sorted from smallest to largest.

Loop Through A TreeMap

You can loop through the entries of a TreeMap with entrySet(). The loop visits entries in sorted key order.

import java.util.Map;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        TreeMap<String, Double> prices = new TreeMap<>();

        prices.put("notebook", 3.50);
        prices.put("pen", 1.25);
        prices.put("folder", 2.00);

        for (Map.Entry<String, Double> entry : prices.entrySet()) {
            System.out.println(entry.getKey() + ": $" + entry.getValue());
        }
    }
}

Output:

folder: $2.0
notebook: $3.5
pen: $1.25

This loop prints the item names alphabetically because the item names are the keys. Use entrySet() when you need both the key and its value.

Find Nearby Keys

TreeMap has navigation methods for finding keys near another key. These methods are useful for schedules, score ranges, and other sorted data.

import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        TreeMap<Integer, String> milestones = new TreeMap<>();

        milestones.put(10, "Warm up");
        milestones.put(30, "Practice");
        milestones.put(60, "Review");
        milestones.put(90, "Quiz");

        System.out.println("Before 60: " + milestones.lowerKey(60));
        System.out.println("After 60: " + milestones.higherKey(60));
        System.out.println("Up to 60: " + milestones.headMap(60, true));
    }
}

Output:

Before 60: 30
After 60: 90
Up to 60: {10=Warm up, 30=Practice, 60=Review}

lowerKey(60) finds the greatest key below 60. higherKey(60) finds the smallest key above 60. The headMap(60, true) call returns a view of entries whose keys are up to and including 60.

Common TreeMap Methods

  • put(key, value) adds or replaces a value for a key.
  • get(key) returns the value for a key, or null if the key is missing.
  • containsKey(key) checks whether a key exists.
  • remove(key) removes a key-value pair.
  • firstKey() returns the smallest key.
  • lastKey() returns the largest key.
  • lowerKey(key) returns the greatest key below the given key.
  • higherKey(key) returns the smallest key above the given key.
  • size() returns the number of key-value pairs.

TreeMap Versus HashMap

Feature TreeMap HashMap
Order Sorted by key No guaranteed order
Lookup style By key, with sorted navigation By key
Common use Maps that need ordered keys or range lookups Fast general key-value lookup

Common Mistakes

  • Forgetting import java.util.TreeMap;.
  • Expecting values to control the order. A TreeMap sorts by keys, not by values.
  • Using keys that cannot be compared. The keys must either have a natural order, such as strings and numbers, or use a custom comparator.
  • Trying to use primitive generic types such as TreeMap<int, String> instead of wrapper types such as TreeMap<Integer, String>.

Takeaway: use TreeMap when you need a map whose keys stay sorted and can be searched by order.