【问题标题】:Java Generics: Sort Map by ValueJava 泛型:按值对映射进行排序
【发布时间】:2013-02-01 23:57:33
【问题描述】:

尝试编译以下对通用地图进行排序的函数时出现此错误:

"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;
    }
}

【问题讨论】:

    标签: java generics map sorted


    【解决方案1】:

    您需要让V 实现Comparable。您可以通过以下方式明确要求它:

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

    或者,您可以将o1.getValue()o2.getValue() 转换为Comparable&lt;V&gt;

    【讨论】:

    • 为获得最佳效果,请使用V extends Comparable&lt;? super V&gt;
    • 越来越神秘了。 Java 什么时候会有一个像样的类型系统?恐怕在我的有生之年没有:)
    • @Anton.Ashanin 这不是必需的,但提供了更大的灵活性。想象CatAnimal implements Comparable&lt;Animal&gt; 的子类:您的方法将无法按值对Map&lt;Object, Cat&gt; 进行排序。但是,如果您将该方法声明为V extends Comparable&lt;? super V&gt;,您现在可以按值对该映射进行排序,因为Cat 实现了Comparable&lt;Animal&gt;,即Comparable&lt;Something super Cat&gt;
    猜你喜欢
    • 1970-01-01
    • 2018-01-15
    • 2021-12-23
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-01
    • 1970-01-01
    相关资源
    最近更新 更多