Here you can find the source of sortMapDescByValue(Map
public static Map<String, Integer> sortMapDescByValue(Map<String, Integer> map)
//package com.java2s; //License from project: Open Source License import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class Main { public static Map<String, Integer> sortMapDescByValue(Map<String, Integer> map) { List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(map.entrySet()); // sort list based on comparator Collections.sort(list, new Comparator<Entry<String, Integer>>() { public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) { return o2.getValue().compareTo(o1.getValue()); }// w w w . ja v a 2 s. c om }); // put sorted list into map again //LinkedHashMap make sure order in which keys were inserted Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>(); for (Iterator<Entry<String, Integer>> it = list.iterator(); it.hasNext();) { Map.Entry<String, Integer> entry = (Map.Entry<String, Integer>) it.next(); sortedMap.put(entry.getKey(), entry.getValue()); } return sortedMap; } }