Java泛型:按值对Map进行排序

3
尝试编译以下通用映射排序函数时,我遇到了以下错误:
"The method compareTo(V) is undefined for the type V"

请帮助让这个工作起来!

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;
    }
}
1个回答

8

您需要使用V实现Comparable接口。您可以通过以下方式显式要求它:

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

或者,您可以将 o1.getValue()o2.getValue() 转换为 Comparable<V>


为了获得最佳结果,请使用V extends Comparable<? super V> - newacct
它变得越来越神秘了。 Java何时才会有一个像样的类型系统?恐怕不在我的有生之年 :) - Anton.Ashanin
@Anton.Ashanin 这不是必须的,但会更加灵活。想象一下,CatAnimal implements Comparable<Animal> 的子类:如果你的方法无法对 Map<Object, Cat> 按值进行排序。但是,如果你将该方法声明为 V extends Comparable<? super V>,那么你现在可以通过值来排序该 Map,因为 Cat 实现了 Comparable<Animal>,即 *Comparable<Something super Cat>*。 - assylias

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接