你可以建立一个TreeSet
,可保证插入顺序:
@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]
(注:[Math.E, Math.PI, Math.UNIVERSAL_ANSWER]
:-)。
PS
的Comparator
:
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());
}
}
来源
2010-01-27 10:28:01
dfa
请问什么整数代表什么?知道这将有助于提出,而不是树形图的另一个数据结构... – pgras 2010-01-27 10:16:07
你能澄清的称号?它不清楚你想要分类的领域。 – cmcginty 2012-06-07 02:10:40