Here you can find the source of sortByValue(Map
public static <K, V extends Comparable<V>> Map<K, V> sortByValue(Map<K, V> map)
//package com.java2s; //License from project: Open Source License import java.util.Collections; import java.util.Comparator; 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 <K, V extends Comparable<V>> Map<K, V> sortByValue(Map<K, V> map) { Comparator<Map.Entry<K, V>> valueComparator = null; valueComparator = new Comparator<Map.Entry<K, V>>() { public int compare(Entry<K, V> o1, Entry<K, V> o2) { return o2.getValue().compareTo(o1.getValue()); }/*from www . jav a 2 s . c o m*/ }; final List<Map.Entry<K, V>> entries = new LinkedList<Map.Entry<K, V>>(map.entrySet()); Collections.sort(entries, valueComparator); final Map<K, V> result = new LinkedHashMap<K, V>(); for (Map.Entry<K, V> entry : entries) result.put(entry.getKey(), entry.getValue()); return result; } }