Java TreeMap
last modified August 28, 2026
In this article we show how to use the Java TreeMap collection.
TreeMap is a map that stores key-value pairs in sorted order. Each
key is associated with one value, and keys in a TreeMap must be
unique. TreeMap implements the SortedMap and
NavigableMap interfaces. It can therefore find entries before or
after a key and create views of a range of keys.
By default, keys are sorted according to their natural ordering. A
Comparator can be supplied to use a different ordering. Basic
operations such as get, put, and remove
take logarithmic time. A TreeMap does not allow a null key when it
uses natural ordering, but it can store null values.
Map.Entry represents a key-value pair. The entrySet
method returns a Set view of the mappings, while
keySet returns a set view of the keys. The views are ordered using
the same ordering as the map.
TreeMap constructors
TreeMap()- constructs an empty map using natural key ordering.TreeMap(Comparator<? super K> comparator)- constructs an empty map using the specified comparator.TreeMap(Map<? extends K,? extends V> m)- constructs a map with the same mappings as the given map.TreeMap(SortedMap<K,? extends V> m)- constructs a map with the same mappings and ordering as the given sorted map.
K is the type of the map keys and V is the type of mapped values.
TreeMap creation
TreeMap is created with the new keyword.
import java.util.Map;
import java.util.TreeMap;
void main() {
Map<String, String> capitals = new TreeMap<>();
capitals.put("svk", "Bratislava");
capitals.put("ger", "Berlin");
capitals.put("ita", "Rome");
System.out.println(capitals);
}
The keys are printed in natural, alphabetical order, regardless of the order in which the entries were inserted.
{ger=Berlin, ita=Rome, svk=Bratislava}
Natural ordering
When no comparator is supplied, every key must implement
Comparable. The map uses compareTo to place keys and
to decide whether two keys are equal. For this reason, a comparator or natural
ordering should be consistent with equals whenever possible.
import java.util.TreeMap;
void main() {
var scores = new TreeMap<String, Integer>();
scores.put("Emma", 91);
scores.put("David", 84);
scores.put("Alice", 96);
scores.forEach((name, score) ->
System.out.printf("%s: %d%n", name, score));
}
The entries are printed in alphabetical order. This is the natural ordering
of the String keys, which implement Comparable.
Alice: 96 David: 84 Emma: 91
Using a Comparator
The comparator constructor is useful when keys should be ordered differently from their natural order. This example stores names in reverse alphabetical order.
import java.util.Comparator;
import java.util.TreeMap;
void main() {
var countries = new TreeMap<String, String>(Comparator.reverseOrder());
countries.put("de", "Germany");
countries.put("sk", "Slovakia");
countries.put("ru", "Russia");
System.out.println(countries);
}
Thanks to the Comparator.reverseOrder comparator, the entries
are printed in reverse alphabetical order.
{sk=Slovakia, ru=Russia, de=Germany}
The firstKey and lastKey methods
The firstKey and lastKey methods return the lowest
and highest keys in the map. They throw NoSuchElementException if
the map is empty.
import java.util.TreeMap;
void main() {
var temperatures = new TreeMap<Integer, String>();
temperatures.put(12, "cold");
temperatures.put(28, "warm");
temperatures.put(21, "mild");
System.out.println(temperatures.firstKey());
System.out.println(temperatures.lastKey());
}
The firstKey method returns the lowest key, which is 12, and
lastKey returns the highest key, which is 28.
12 28
Navigable methods
NavigableMap provides methods for finding neighboring keys.
floorKey returns the greatest key less than or equal to a given
key. ceilingKey returns the least key greater than or equal to
it. The related lowerKey and higherKey methods use
strictly less-than and greater-than comparisons.
import java.util.TreeMap;
void main() {
var grades = new TreeMap<Integer, String>();
grades.put(60, "D");
grades.put(70, "C");
grades.put(80, "B");
grades.put(90, "A");
System.out.println(grades.floorEntry(75));
System.out.println(grades.ceilingEntry(75));
System.out.println(grades.lowerKey(80));
System.out.println(grades.higherKey(80));
}
The floorEntry method finds the entry with the greatest key less
than or equal to 75, which is 70=C. The ceilingEntry
method finds the entry with the least key greater than or equal to 75, which
is 80=B. The lowerKey and higherKey
methods use strict comparisons.
70=C 80=B 70 90
Range views
The subMap, headMap, and tailMap
methods return live views of parts of a TreeMap. Changes made
through a view are also made in the original map. The four-argument
subMap lets us choose whether each endpoint is included.
import java.util.NavigableMap;
import java.util.TreeMap;
void main() {
var products = new TreeMap<Integer, String>();
products.put(100, "pen");
products.put(200, "notebook");
products.put(300, "backpack");
products.put(400, "lamp");
NavigableMap<Integer, String> selected =
products.subMap(200, true, 400, false);
System.out.println(selected);
selected.remove(200);
System.out.println(products);
}
The subMap method returns a view with keys from 200, inclusive,
to 400, exclusive. Removing the entry with key 200 through the view deletes
it from the original map as well, because the view is live.
{200=notebook, 300=backpack}
{100=pen, 300=backpack, 400=lamp}
Iteration over a TreeMap
Iteration over entrySet visits entries in key order. The same
ordering is used by keySet, values, and
forEach.
import java.util.Map;
import java.util.TreeMap;
void main() {
Map<String, String> capitals = new TreeMap<>();
capitals.put("svk", "Bratislava");
capitals.put("ger", "Berlin");
capitals.put("ita", "Rome");
for (var pair: capitals.entrySet()) {
System.out.printf("%s: %s%n", pair.getKey(), pair.getValue());
}
}
Although the entries were inserted in a different order, they are printed in ascending key order.
ger: Berlin ita: Rome svk: Bratislava
TreeMap versus HashMap
Use TreeMap when keys must remain sorted or when you need range
and neighbor queries. Use HashMap when ordering is not required
and average constant-time basic operations are more important. Neither map is
thread-safe; use an appropriate concurrent map or external synchronization
when multiple threads modify a map.
| Feature | TreeMap | HashMap |
|---|---|---|
| Ordering | Sorted by key | No ordering guarantee |
| Basic operations | O(log n) | O(1) average |
| Null key | Not with natural ordering | One null key is allowed |
| Range queries | Supported | Not supported directly |
Source
Java TreeMap - language reference
In this article we have presented the Java TreeMap collection.
Author
List all Java tutorials.