Sorting HashMap by value in Java:
public class HashMapSortByValue {
public static void main(String[] args) {
HashMap<Long,String> unsortMap = new HashMap<Long,String>();
unsortMap.put(5l,"B");
unsortMap.put(8l,"A");
unsortMap.put(2l, "D");
unsortMap.put(7l,"C" );
System.out.println("Before sorting......");
System.out.println(unsortMap);
HashMap<Long,String> sortedMapAsc = sortByComparator(unsortMap);
System.out.println("After sorting......");
System.out.println(sortedMapAsc);
}
public static HashMap<Long,String> sortByComparator(
HashMap<Long,String> unsortMap) {
List<Map.Entry<Long,String>> list = new LinkedList<Map.Entry<Long,String>>(
unsortMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Long,String>> () {
public int compare(Map.Entry<Long,String> o1, Map.Entry<Long,String> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
HashMap<Long,String> sortedMap = new LinkedHashMap<Long,String>();
for (Entry<Long,String> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
}