comparator for Map.Entry

后端 未结 1 972
死守一世寂寞
死守一世寂寞 2021-02-10 17:25

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 Collection

相关标签:
1条回答
  • 2021-02-10 17:39

    You probably want this:

    // 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 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.

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

    You can now use the above ScoreComparator as such:

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

    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());
        }   
    }
    
    0 讨论(0)
提交回复
热议问题