Here you can find the source of sortMapByValues(Map
Borrowed from http://javarevisited.blogspot.com/2012/12/how-to-sort-hashmap-java-by-key-and-value.html Java method to sort Map in Java by value e.g.
public static <K, V extends Comparable> Map<K, V> sortMapByValues(Map<K, V> map, final boolean inverted)
//package com.java2s; //License from project: Open Source License import java.util.*; public class Main { /**// w w w. j a v a 2 s . c om * Borrowed from http://javarevisited.blogspot.com/2012/12/how-to-sort-hashmap-java-by-key-and-value.html * Java method to sort Map in Java by value e.g. HashMap or Hashtable * throw NullPointerException if Map contains null values * It also sort values even if they are duplicates */ public static <K, V extends Comparable> Map<K, V> sortMapByValues(Map<K, V> map, final boolean inverted) { List<Map.Entry<K, V>> entries = new LinkedList<Map.Entry<K, V>>(map.entrySet()); Collections.sort(entries, new Comparator<Map.Entry<K, V>>() { @Override public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) { // Descending. if (!inverted) return o2.getValue().compareTo(o1.getValue()); else return o1.getValue().compareTo(o2.getValue()); } }); //LinkedHashMap will keep the keys in the order they are inserted //which is currently sorted on natural ordering Map<K, V> sortedMap = new LinkedHashMap<K, V>(); for (Map.Entry<K, V> entry : entries) { sortedMap.put(entry.getKey(), entry.getValue()); } return sortedMap; } }