<p>I am relatively new to Java, and often find that I need to sort a <code>Map&lt;Key, Value&gt;</code> on the values.</p>

<p>Since the values are not unique, I find myself converting the <code>keySet</code> into an <code>array</code>, and sorting that array through <strong>array sort</strong> with a <strong>custom comparator</strong> that sorts on the value associated with the key.</p>

<p>Is there an easier way?</p>

From
http://www.programmersheaven.com/download/49349/download.aspx
```
```
private static <K, V> Map<K, V> sortByValue(Map<K, V> map) {
    List<Entry<K, V>> list = new LinkedList<>(map.entrySet());
    Collections.sort(list, new Comparator<Object>() {
        @SuppressWarnings("unchecked")
        public int compare(Object o1, Object o2) {
            return ((Comparable<V>) ((Map.Entry<K, V>) (o1)).getValue()).compareTo(((Map.Entry<K, V>) (o2)).getValue());
        }
    });

    Map<K, V> result = new LinkedHashMap<>();
    for (Iterator<Entry<K, V>> it = list.iterator(); it.hasNext();) {
        Map.Entry<K, V> entry = (Map.Entry<K, V>) it.next();
        result.put(entry.getKey(), entry.getValue());
    }

    return result;
}
```
```