How to Iterate TreeMap Keys in Reverse Order with Example

In the last tutorial we have discussed how to sort TreeMap by value. TreeMap elements are sorted in ascending order of keys by default. What if we want to sort it by descending order of keys. In this tutorial we will sort the TreeMap keys in descending order.

Read Also :   How to iterate a TreeMap in Java

Program to Iterate TreeMap in Reverse Order


import java.util.*;

 public class TreeMapKeysInDescendingOrder {
    public static void main(String args[]) {
        
    // Declaring a TreeMap of String keys and String values
    TreeMap<String, String> treemap = 
                new TreeMap<String, String>(Collections.reverseOrder());
    // Add Key-Value pairs to TreeMap
    treemap.put("Key1", "Pear");
    treemap.put("Key2", "Apple");
    treemap.put("Key3", "Orange");
    treemap.put("Key4", "Papaya");
    treemap.put("Key5", "Banana");
    
    
    // Get Set of entries
    Set set = treemap.entrySet();
    // Get iterator
    Iterator it = set.iterator();
    // Show TreeMap elements
    System.out.println("TreeMap contains: ");
    while(it.hasNext()) {
      Map.Entry pair = (Map.Entry)it.next();
      System.out.print("Key is: "+pair.getKey() + " and ");
      System.out.println("Value is: "+pair.getValue());
    }
  }
} 


Output
TreeMap contains: 
Key is: Key5 and Value is: Banana
Key is: Key4 and Value is: Papaya
Key is: Key3 and Value is: Orange
Key is: Key2 and Value is: Apple
Key is: Key1 and Value is: Pear



About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry