Map.Entry< K,V>的比较器。 [英] comparator for Map.Entry<K,V>

查看:90
本文介绍了Map.Entry< K,V>的比较器。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Map,其枚举类型为键,Double为值。我想根据Double值对此进行排序。因此,我获得了条目集,并想将 Collections.sort()与比较器一起使用。我为比较器提供了以下代码

I have a Map with an enumeration type as the key and Double as the value. I want to sort this based on the Double values. So I got the entry set and want to use Collections.sort() with a comparator. I have the following code for the comparator

class ScoreComparator<Map.Entry<K, V>> implements Comparator<Map.Entry<K, V>> {
    public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
        return o1.getValue().compareTo(o2.getValue());
    }   
}

我收到以下错误消息


  1. 令牌。的语法错误,扩展了预期的内容(第1行)

  2. 类型参数Map隐藏类型Map< K,V> (第1行)

  3. 由于上述两个错误,K和V无法解析为类型(第3,4行)。

我无法解决此问题。非常感谢您的帮助。

I am unable to resolve this. Any help is highly appreciated. Thanks in advance.

推荐答案

您可能想要这样:

// Declare K and V as generic type parameters to ScoreComparator
class ScoreComparator<K, V extends Comparable<V>> 

// Let your class implement Comparator<T>, binding Map.Entry<K, V> to T
implements Comparator<Map.Entry<K, V>> {
    public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {

        // Call compareTo() on V, which is known to be a Comparable<V>
        return o1.getValue().compareTo(o2.getValue());
    }   
}

ScoreComparator 接受两个通用类型参数 K V Map.Entry< K,V> 不是有效的泛型类型定义,但是您可以很好地使用它来绑定到 Comparator< T> T 类型。

ScoreComparator takes two generic type arguments K and V. Map.Entry<K, V> is not a valid generic type definition, but you may well use it to bind to Comparator<T>'s T type.

请注意 V 必须扩展 Comparable< V> ,以便能够在<$上调用 compareTo() c $ c> o1.getValue()。

Note that V must extend Comparable<V>, in order to be able to call compareTo() on o1.getValue().

您现在可以使用上面的 ScoreComparator 这样:

You can now use the above ScoreComparator as such:

new ScoreComparator<String, String>();
new ScoreComparator<Long, Integer>();
// etc...

注意,从当前的实现中,您可能不会甚至不需要 K 参数。替代方案:

Note, from your current implementation, you probably don't even need the K parameter. An alternative:

class ScoreComparator<V extends Comparable<V>> 
implements Comparator<Map.Entry<?, V>> {
    public int compare(Map.Entry<?, V> o1, Map.Entry<?, V> o2) {

        // Call compareTo() on V, which is known to be a Comparable<V>
        return o1.getValue().compareTo(o2.getValue());
    }   
}

这篇关于Map.Entry&lt; K,V&gt;的比较器。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆