Tuesday, 5 December 2017

How to Iterate Through a TreeMap in Reverse Order in Java

       A TreeMap stores its keys in sorted order. By default, it sorts the keys according to their natural ordering. Alternatively, you can provide a custom Comparator when creating the TreeMap, and the keys will be sorted according to that comparator.

If you want the TreeMap to maintain its keys in reverse order, pass Collections.reverseOrder() as the comparator to the TreeMap constructor.

The signature of the reverseOrder() method is as follows:

public static Comparator reverseOrder():

Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.

Example:

package com.test;

import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class SortTreeMap {

      public static void main(String[] args) {
  
             TreeMap<String, Integer> treeMap = new TreeMap<String, Integer>(
                                          Collections.reverseOrder());
  
             //add elements into the Map
             treeMap.put("Mahesh", 1);
             treeMap.put("Anil", 2);
             treeMap.put("Raj", 3);
             treeMap.put("Anand", 4);
  
             Iterator it = treeMap.entrySet().iterator();
  
             while (it.hasNext()) {
                   Map.Entry mp = (Map.Entry) it.next();
                   System.out.println("Key :" +mp.getKey()+"  Value: "+mp.getValue());
             }
      }
}

Output:--Key :Raj  Value: 3
              Key :Mahesh  Value: 1
              Key :Anil  Value: 2
              Key :Anand  Value: 4



Related Post:--
Internal Implementation of TreeMap in Java 
How HashMap works internally in Java?  
Internal implementation of ArrayList in Java  
Internal Implementation of LinkedList in Java  

No comments:

Post a Comment