Tuesday, 5 December 2017

How to iterate the TreeMap in reverse order in Java

      The TreeMap will give the sorting order i.e natural sorting.  It will sort the key based on Comparator passed in the constructor while creating the TreeMap.
      But If you want to iterate the TreeMap in reverse order then pass Collections.reverseOrder() argument in the constructor of  TreeMap.

Signature of reverseOrder() method as,

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