Descending order sorting a HashMap,TreeMap in Java


Here is the code
Public static void mai(String[] args) { 
TreeMap<String, Integer> treeMap = new TreeMap<String, Integer>(); Iterator<Entry<String, Integer>> entries = map.entrySet().iterator();while (entries.hasNext()) { Entry<String, Integer> entry = entries.next(); treeMap.put(entry.getKey(), entry.getValue());}SortedSet<Map.Entry<String,Integer>> sm = new TreeSet<Map.Entry<String ,Integer>>();sm =   entriesSortedByValues(treeMap);  // This is sorted map in descending order
}//----------------
static <K,V extends Comparable<? super V>>
SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
       new Comparator<Map.Entry<K,V>>() {
@Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
    int res = e1.getValue().compareTo(e2.getValue());
    return res != 0 ? res : 1
   }        
  }    
);
sortedEntries.addAll(map.entrySet());   
return sortedEntries;
}


Happy coding

Comments

Popular Posts