Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
java.util.TreeMap
is a class in Java that implements the NavigableMap
interface and provides a sorted map. It stores the key-value pairs in a sorted order based on the natural ordering of the keys or a custom comparator.
descendingMap()
and descendingKeyset()
are two methods provided by the TreeMap
class to get a reverse order view of the map.
descendingMap()
The descendingMap()
method returns a NavigableMap
instance that has the reverse order of the original map. The returned map is backed by the original map, so any changes made to the original map will be reflected in the returned map and vice versa.
// Creating a TreeMap
TreeMap<Integer, String> treeMap = new TreeMap<>();
// Adding elements to the TreeMap
treeMap.put(1, "One");
treeMap.put(2, "Two");
treeMap.put(3, "Three");
treeMap.put(4, "Four");
treeMap.put(5, "Five");
// Getting the descending map
NavigableMap<Integer, String> descendingMap = treeMap.descendingMap();
// Printing the descending map
System.out.println("Descending Map: " + descendingMap);
Output:
Descending Map: {5=Five, 4=Four, 3=Three, 2=Two, 1=One}
descendingKeyset()
The descendingKeyset()
method returns a NavigableSet
instance that has the reverse order of the original map's keys. The returned set is backed by the original map, so any changes made to the original map will be reflected in the returned set and vice versa.
// Creating a TreeMap
TreeMap<Integer, String> treeMap = new TreeMap<>();
// Adding elements to the TreeMap
treeMap.put(1, "One");
treeMap.put(2, "Two");
treeMap.put(3, "Three");
treeMap.put(4, "Four");
treeMap.put(5, "Five");
// Getting the descending key set
NavigableSet<Integer> descendingKeySet = treeMap.descendingKeySet();
// Printing the descending key set
System.out.println("Descending Key Set: " + descendingKeySet);
Output:
Descending Key Set: [5, 4, 3, 2, 1]
Both descendingMap()
and descendingKeyset()
methods can be useful in scenarios where we need to iterate over the map in reverse order.