我需要一个 TreeMap 的比较器。我应该在我的 TreeMap 的构造函数中匿名写这个吗?我怎么能写我的比较器。目前,Java 不喜欢我的代码(我可以匿名这样做吗?):
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关于值(value)观。
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.
要对值进行排序,您需要 SortedSet .使用
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 比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12947088/