Java – Sorting HashMap by Value code.

//largest to smallest
private HashMap<String, Integer> sortByValueInverse(HashMap<String, Integer> unsortMap) {

    // Convert Map to List
    List<Map.Entry<String, Integer>> list
            = new LinkedList<Map.Entry<String, Integer>>(unsortMap.entrySet());

    // Sort list with comparator, to compare the Map values
    Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
        public int compare(Map.Entry<String, Integer> o1,
                Map.Entry<String, Integer> o2) {
            return (o2.getValue()).compareTo(o1.getValue());
        }
    });

    // Convert sorted map back to a Map
    HashMap<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
    for (Iterator<Map.Entry<String, Integer>> it = list.iterator(); it.hasNext();) {
        Map.Entry<String, Integer> entry = it.next();
        sortedMap.put(entry.getKey(), entry.getValue());
    }
    return sortedMap;
}



Java – Print Top 10 HashMap by Value code

    private void printTop10Largest(HashMap<String, Integer> notSortedMap) {
        HashMap<String, Integer> valueSortedMap = sortByValueInverse(notSortedMap);
        Iterator<String> it = valueSortedMap.keySet().iterator();
        String key;
        int value;

        for (int i = 1; i < 11; i++) {
            key = it.next();
            value = valueSortedMap.get(key);
            System.out.println(i + "," + key + "," + value);
        }
    }