TreeMap:使用键与值一起移动的地图的值排序 [英] TreeMap: Sort values of a map with keys moving along with values
问题描述
我有以下TreeMap:
i have the following TreeMap:
TreeMap<Integer, Double> map;
Double值不唯一。
the Double values are not unique.
我使用整数键和函数firstEntry()和higherEntry()来迭代地图,并修改Double值。
i iterate through the map using Integer keys and the functions firstEntry() and higherEntry() and modify the Double values.
现在我想列出对的值按顺序降低Double值。
这是最好的方法?
Now i want to list the values of the pairs in the order of decreasing Double values. what is the best way to do this?
这些整数键对我很重要,因为Double值不是唯一的,我不能有一个双键
those Integer keys are important to me and because the Double values are not unique, i cannot have a Double key.
更新:
更多说明
这是经典的问题。让我们说,学生的成绩是关键,他们的百分比是价值。现在按百分比排序,然后我们应该能够知道其百分比是多少。因此我需要整数键。
Update: More Explanation it is the classic problem. lets say rollnos of students is the key and their percentage is the value. now sort by percentage and then we should be able to tell whose percentage is it. therefore i need the integer key.
推荐答案
可以构建一个 TreeSet
,确保插入顺序:
you can build a TreeSet
, that guarantees insertion order:
@Test
public void treeMapSortedByValue() {
// given the following map:
TreeMap<Integer, Double> map = new TreeMap<Integer, Double>();
map.put(2, Math.E);
map.put(1, Math.PI);
map.put(3, 42.0);
// build a TreeSet of entries
Set<Map.Entry<Integer, Double>> sortedEntries = new TreeSet<Map.Entry<Integer, Double>>(new DoubleComparator());
sortedEntries.addAll(map.entrySet());
// optionally you can build a List<Double> with the sorted
List<Double> doubles = new LinkedList<Double>();
for (Map.Entry<Integer, Double> entry : sortedEntries) {
doubles.add(entry.getValue());
}
}
这应该给你: [2.718281828459045,3.141592653589793,42.0]
(nb: [Math.E,Math.PI,Math.UNIVERSAL_ANSWER]
:-)。
this should give you: [2.718281828459045, 3.141592653589793, 42.0]
(nb: [Math.E, Math.PI, Math.UNIVERSAL_ANSWER]
:-).
PS
比较器
:
class DoubleComparator implements Comparator<Map.Entry<Integer, Double>> {
@Override
public int compare(Entry<Integer, Double> o1, Entry<Integer, Double> o2) {
return Double.compare(o1.getValue(), o2.getValue());
}
}
这篇关于TreeMap:使用键与值一起移动的地图的值排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!