Java TreeMap
Java TreeMap Class
Last Updated : 29 Mar 2026
Java TreeMap is used for storing key-value pairs in a sorted order which is useful when data needs to be accessed in a structured and ordered way. It is commonly used in applications where quick search, insertion, and deletion operations are required along with sorting.
In this chapter, you will learn about the Java TreeMap class, its working, features, and how it maintains sorted key-value pairs using a red-black tree.
What is Java TreeMap?
Java TreeMap is a class in the java.util package that implements the NavigableMap interface and extends the AbstractMap class. It is based on a red-black tree data structure and stores key-value pairs in sorted (ascending) order.
TreeMap allows only unique keys, does not permit null keys, but can contain multiple null values. It is non-synchronized and is mainly used when sorted data is required.
TreeMap Class Hierarchy
The TreeMap is part of the Collections Framework and follows a hierarchical structure where it extends the AbstractMap class and implements the NavigableMap interface. NavigableMap further extends SortedMap, which is a part of the Map interface. This hierarchy enables TreeMap to store elements in a sorted manner and provide navigation methods such as finding higher, lower, or nearest keys efficiently.

Key Points about TreeMap
The important points about Java TreeMap class are:
- The TreeMap stores data in the form of key-value pairs, where each key is associated with a specific value.
- It ensures that all keys are unique, which means duplicate keys are not allowed.
- It maintains elements in ascending order automatically using a red-black tree data structure.
- It provides efficient performance for operations such as search, insertion, and deletion.
- It does not allow null keys, but it supports multiple null values.
- It is non-synchronized, which makes it faster but not thread-safe by default.
TreeMap Class Declaration
Let's see the declaration for java.util.TreeMap class.
TreeMap Class Parameters
Let's see the Parameters for java.util.TreeMap class.
- K: It is the type of keys maintained by this map.
- V: It is the type of mapped values.
Constructors of TreeMap Class
Java TreeMap provides multiple constructors to create and initialize a TreeMap in different ways.
1. TreeMap()
This constructor constructs an empty TreeMap that is sorted according to the natural ordering of its keys.
Here is syntax:
2. TreeMap(Comparator comparator)
This constructor constructs an empty TreeMap that is sorted according to the specified comparator.
Here is syntax:
3. TreeMap(Map m)
This constructor constructs a TreeMap and initializes it with the entries from the specified map, sorted according to the natural ordering of the keys.
Here is syntax:
4. TreeMap(SortedMapm)
This constructor constructs a TreeMap and initializes it with the entries from the specified sorted map, maintaining the same ordering as the given map.
Here is syntax:
5. TreeMap(Collection c)
This constructor constructs a TreeMap containing the elements of the specified collection, sorted according to their natural ordering.
Here is syntax:
6. TreeMap(SortedMapm, Comparator comparator)
Constructs a TreeMap with the entries from the specified sorted map and sorts them using the provided comparator.
Here is syntax:
Methods of TreeMap Class
The TreeMap provides a variety of methods to perform operations such as insertion, deletion, searching, and navigation of elements in a sorted key-value structure.
The following table lists the commonly used methods of the TreeMap class along with their descriptions:
| Method | Description |
|---|---|
| Map.Entry<K,V> ceilingEntry(K key) | It returns the key-value pair having the least key, greater than or equal to the specified key, or null if there is no such key. |
| K ceilingKey(K key) | It returns the least key, greater than the specified key or null if there is no such key. |
| void clear() | It removes all the key-value pairs from a map. |
| Object clone() | It returns a shallow copy of TreeMap instance. |
| Comparator<? super K> comparator() | It returns the comparator that arranges the key in order, or null if the map uses the natural ordering. |
| NavigableSet<K> descendingKeySet() | It returns a reverse order NavigableSet view of the keys contained in the map. |
| NavigableMap<K,V> descendingMap() | It returns the specified key-value pairs in descending order. |
| Map.EntryfirstEntry() | It returns the key-value pair having the least key. |
| Map.Entry<K,V> floorEntry(K key) | It returns the greatest key, less than or equal to the specified key, or null if there is no such key. |
| void forEach(BiConsumer<? super K,? super V> action) | It performs the given action for each entry in the map until all entries have been processed or the action throws an exception. |
| SortedMap<K,V> headMap(K toKey) | It returns the key-value pairs whose keys are strictly less than toKey. |
| NavigableMap<K,V> headMap(K toKey, boolean inclusive) | It returns the key-value pairs whose keys are less than (or equal to if inclusive is true) toKey. |
| Map.Entry<K,V> higherEntry(K key) | It returns the least key strictly greater than the given key, or null if there is no such key. |
| K higherKey(K key) | It is used to return true if this map contains a mapping for the specified key. |
| SetkeySet() | It returns the collection of keys exist in the map. |
| Map.Entry<K,V> lastEntry() | It returns the key-value pair having the greatest key, or null if there is no such key. |
| Map.Entry<K,V> lowerEntry(K key) | It returns a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key. |
| K lowerKey(K key) | It returns the greatest key strictly less than the given key, or null if there is no such key. |
| NavigableSet<K> navigableKeySet() | It returns a NavigableSet view of the keys contained in this map. |
| Map.Entry<K,V> pollFirstEntry() | It removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty. |
| Map.Entry<K,V> pollLastEntry() | It removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty. |
| V put(K key, V value) | It inserts the specified value with the specified key in the map. |
| void putAll(Map<? extends K,? extends V> map) | It is used to copy all the key-value pair from one map to another map. |
| V replace(K key, V value) | It replaces the specified value for a specified key. |
| boolean replace(K key, V oldValue, V newValue) | It replaces the old value with the new value for a specified key. |
| void replaceAll(BiFunction<? super K,? super V,? extends V> function) | It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception. |
| NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) | It returns key-value pairs whose keys range from fromKey to toKey. |
| SortedMap<K,V> subMap(K fromKey, K toKey) | It returns key-value pairs whose keys range from fromKey, inclusive, to toKey, exclusive. |
| SortedMap<K,V> tailMap(K fromKey) | It returns key-value pairs whose keys are greater than or equal to fromKey. |
| NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) | It returns key-value pairs whose keys are greater than (or equal to, if inclusive is true) fromKey. |
| boolean containsKey(Object key) | It returns true if the map contains a mapping for the specified key. |
| boolean containsValue(Object value) | It returns true if the map maps one or more keys to the specified value. |
| K firstKey() | It is used to return the first (lowest) key currently in this sorted map. |
| V get(Object key) | It is used to return the value to which the map maps the specified key. |
| K lastKey() | It is used to return the last (highest) key currently in the sorted map. |
| V remove(Object key) | It removes the key-value pair of the specified key from the map. |
| Set<Map.Entry<K,V>> entrySet() | It returns a set view of the mappings contained in the map. |
| int size() | It returns the number of key-value pairs exists in the hashtable. |
| Collectionvalues() | It returns a collection view of the values contained in the map. |
Examples of Java TreeMap Class
The following examples demonstrate how to use Java TreeMap for storing, removing, and navigating key-value pairs.
Example 1: Storing and Iterating TreeMap Elements
This example demonstrates how to store key-value pairs in a TreeMap and iterate through them.
Output:
100 Amit 101 Vijay 102 Ravi 103 Rahul
Example 2: Removing Elements from TreeMap
This example demonstrates how to remove an element using the remove() method.
Output:
Before invoking remove() method 100 Amit 101 Vijay 102 Ravi 103 Rahul After invoking remove() method 100 Amit 101 Vijay 103 Rahul
Example 3: Using NavigableMap Methods
This example demonstrates various navigation methods such as descendingMap(), headMap(), tailMap(), and subMap().
Output:
descendingMap: {103=Rahul, 102=Ravi, 101=Vijay, 100=Amit}
headMap: {100=Amit, 101=Vijay, 102=Ravi}
tailMap: {102=Ravi, 103=Rahul}
subMap: {101=Vijay, 102=Ravi}
Example 4: Using SortedMap Methods
This example demonstrates how to use SortedMap methods like headMap(), tailMap(), and subMap().
Output:
headMap: {100=Amit, 101=Vijay}
tailMap: {102=Ravi, 103=Rahul}
subMap: {100=Amit, 101=Vijay}
Difference Between HashMap and TreeMap
The following table highlights the key differences between HashMap and TreeMap:
| HashMap | TreeMap |
|---|---|
| HashMap does not guarantee a sorted order of elements. | TreeMap guarantees a sorted order of elements based on the natural ordering of keys or a custom comparator. |
| HashMap is generally faster for insertion and retrieval operations, especially for large datasets. | TreeMap offers efficient range queries and operations like finding the closest key. |
| HashMap uses hashing for storing key-value pairs, providing constant-time performance for basic operations (e.g., get, put, remove) on average. | TreeMap uses a red-black tree internally, resulting in logarithmic-time complexity for most operations, making it slightly slower than HashMap for basic operations. |
| Iterating over elements in a HashMap does not guarantee any specific order. | Iterating over elements in a TreeMap results in sorted order based on the keys. |
| HashMap allows null values, and multiple null values can be associated with different keys. | TreeMap allows null values but not null keys. |
| HashMap is not synchronized, making it not thread-safe. | TreeMap is not synchronized, making it not thread-safe. |
| HashMap is part of the java.util package. | TreeMap is part of the java.util package and implements the NavigableMap interface. |
Complete Example: Storing Custom Objects (Book) in TreeMap
This example demonstrates how to store and retrieve objects of a custom class using a TreeMap.
Output:
1 Details: 101 Let us C Yashwant Kanetkar BPB 8 2 Details: 102 Data Communications & Networking Forouzan Mc Graw Hill 4 3 Details: 103 Operating System Galvin Wiley 6
Explanation
This example shows how a TreeMap can be used to store custom objects as values while maintaining the keys in sorted order. It also demonstrates how to traverse the map and access both keys and their corresponding object values.