Java TreeMap Comparator [英] Java TreeMap Comparator
问题描述
我需要一个TreeMap的比较器。我应该在我的TreeMap的构造函数中匿名编写吗?我怎么能写我的比较器。目前,Java不喜欢我的代码(我可以匿名吗?):
I need a comparator for a TreeMap. Should I write this anonymously in the constructor for my TreeMap? How else could I write my comparator. Currently, Java does not like my code (can I do this anonymously?):
SortedMap<String, Double> myMap =
new TreeMap<String, Double>(new Comparator<Entry<String, Double>>()
{
public int compare(Entry<String, Double> o1, Entry<String, Double> o2)
{
return o1.getValue().compareTo(o2.getValue());
}
});
- 我可以匿名进行上述操作吗?
- 我怎么能这样做?
- 我想按价值而非按键排序myMap
推荐答案
你无法排序 TreeMap。
You can not sort TreeMap on values.
基于红黑树的NavigableMap实现。地图根据其键的自然顺序排序,或者由地图创建时提供的比较器排序,具体取决于使用的构造函数
您需要提供比较器
forComparator<?超级K>
所以你的比较器应该按键进行比较。
A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used You will need to provide
comparator
forComparator<? super K>
so your comparator should compare on keys.
要提供你需要的值的排序< a href =http://docs.oracle.com/javase/6/docs/api/java/util/SortedSet.html> SortedSet 。使用
To provide sort on values you will need SortedSet. Use
SortedSet<Map.Entry<String, Double>> sortedset = new TreeSet<Map.Entry<String, Double>>(
new Comparator<Map.Entry<String, Double>>() {
@Override
public int compare(Map.Entry<String, Double> e1,
Map.Entry<String, Double> e2) {
return e1.getValue().compareTo(e2.getValue());
}
});
sortedset.addAll(myMap.entrySet());
举个例子
SortedMap<String, Double> myMap = new TreeMap<String, Double>();
myMap.put("a", 10.0);
myMap.put("b", 9.0);
myMap.put("c", 11.0);
myMap.put("d", 2.0);
sortedset.addAll(myMap.entrySet());
System.out.println(sortedset);
输出:
[d=2.0, b=9.0, a=10.0, c=11.0]
这篇关于Java TreeMap Comparator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!