We can use descendingMap() method to reverse the map object in java.
Syntax:
treeMap.descendingMap();
Example
package com.w3schools; import java.util.Map; import java.util.TreeMap; public class Test { public static void main(String args[]){ //Create TreeMap object. TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>(); //Add objects to the TreeMap. treeMap.put(4, "Roxy"); treeMap.put(2, "Sunil"); treeMap.put(5, "Sandy"); treeMap.put(1, "Munish"); treeMap.put(3, "Pardeep"); //Print the TreeMap object. System.out.println("TreeMap elements:"); System.out.println(treeMap); //Reverse treemap elements Map<Integer, String> reverseTreeMap = treeMap.descendingMap(); System.out.println("Reverse Map Content: "); System.out.println(reverseTreeMap); } } |
Output
TreeMap elements: {1=Munish, 2=Sunil, 3=Pardeep, 4=Roxy, 5=Sandy} Reverse Map Content: {5=Sandy, 4=Roxy, 3=Pardeep, 2=Sunil, 1=Munish} |