In Java, descendingMap() returns a reverse-order view of a TreeMap: iterating it visits the keys from highest to lowest. Nothing is copied or re-sorted; the view reads the same tree backwards.
The view is live and fully functional. It returns NavigableMap, so it has its own firstKey, floorKey, headMap, and so on, all interpreted in the reversed order. The method was added in Java 6.
An instance method of java.util.TreeMap, added in Java 6 (JDK 1.6) with the NavigableMap interface. A TreeMap keeps its key/value pairs sorted by key in a red-black tree, so lookups and updates take O(log n) time; it is not thread-safe.
Syntax
Call it on the map, then use the result like any NavigableMap.
Java
TreeMap<Integer, String> scores = new TreeMap<>();
NavigableMap<Integer, String> highToLow = scores.descendingMap();
for (Map.Entry<Integer, String> e : highToLow.entrySet()) { /* largest key first */ }
Call
What it does
map.descendingMap()
Live view in reverse key order.
map.descendingMap().firstKey()
The original map's highest key.
map.descendingMap().descendingMap()
Back to the original (ascending) order.
Since Java 21, TreeMap.reversed() (from SequencedMap) gives the same reverse view. On Java 8 to 17, descendingMap() is the way to go.
Library declarations
Java
// java.util.TreeMap<K, V>
public NavigableMap<K, V> descendingMap()
// Declared in NavigableMap<K, V> (Java 6)
Parameters
Parameter
Description
(none)
descendingMap takes no parameters.
Return Value
Return Value
Description
NavigableMap<K, V>
A live view of the same mappings, ordered from highest key to lowest.
"First" follows the view's order. The descending view starts at 30, so its firstKey() is the map's largest key.
Floor rounds the other way. In the view, "less than or equal" means "at or after in descending order", so floorKey(25) moves up to 30, exactly what ceilingKey(25) gives on the map.
Head means the front of the view.down.headMap(20) holds the keys before 20 in descending order, which is only 30.
Frequently Asked Questions
Loop over map.descendingMap().entrySet(), or over descendingKeySet() if you only need the keys.
No. It is a live view over the same tree, created in constant time.
Yes. put, remove, and clear on the view change the backing map.
Navigation follows the view's reversed order, so floor and ceiling (and lower and higher) swap roles compared with the original map.
Use descendingMap() when you sometimes need the reverse order; build the map with Collections.reverseOrder() when it should always be reversed.