comparator for Map.Entry

后端 未结 1 971
死守一世寂寞
死守一世寂寞 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> 
    
    // Let your class implement Comparator, binding Map.Entry to T
    implements Comparator> {
        public int compare(Map.Entry o1, Map.Entry o2) {
    
            // Call compareTo() on V, which is known to be a Comparable
            return o1.getValue().compareTo(o2.getValue());
        }   
    }
    

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

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

    You can now use the above ScoreComparator as such:

    new ScoreComparator();
    new ScoreComparator();
    // etc...
    

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

    class ScoreComparator> 
    implements Comparator> {
        public int compare(Map.Entry o1, Map.Entry o2) {
    
            // Call compareTo() on V, which is known to be a Comparable
            return o1.getValue().compareTo(o2.getValue());
        }   
    }
    

    0 讨论(0)
提交回复
热议问题