Anton.Ashanin
Anton.Ashanin

Reputation: 33

Java Generics: Sort Map by Value

Trying to compile the following function that sorts a generic map I get this error:

"The method compareTo(V) is undefined for the type V"

Please help to make this work!

public class CollectionsPlus<K,V> {

    /**
     * Sort map by value
     * @param map
     * @return
     */
    public static<K,V> Map<K, V> sortMapByValue(Map<K, V> map) {
        List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(
                map.entrySet());
        Collections.sort(list,
                new Comparator<Map.Entry<K, V>>() {
                    public int compare(Map.Entry<K, V> o1,
                            Map.Entry<K, V> o2) {
                        return (o2.getValue().compareTo(o1.getValue()));
                    }
                });

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

Upvotes: 3

Views: 2191

Answers (1)

assylias
assylias

Reputation: 328659

You need to have V implement Comparable. You can explicitly require it by writing:

public static<K, V extends Comparable<V>> Map<K, V> sortMapByValue(Map<K, V> map)

Alternatively, you can cast o1.getValue() and o2.getValue() to Comparable<V>.

Upvotes: 8

Related Questions