Map<Integer, String> map = new TreeMap<Integer, String>();
// Add Items to the TreeMap
map.put(new Integer(8), "Eight");
map.put(new Integer(9), "Nine");
map.put(new Integer(1), "One");
map.put(new Integer(4), "Four");
map.put(new Integer(10), "Ten");
map.put(new Integer(5), "Five");
map.put(new Integer(6), "Six");
map.put(new Integer(2), "Two");
map.put(new Integer(3), "Three");
map.put(new Integer(7), "Seven");
keys = map.keySet();
for (Iterator i = keys.iterator(); i.hasNext();) {
Integer key = (Integer) i.next();
String value = (String) map.get(key);
System.out.println(key + " = " + value);
}
我想反转这种整数种类的TreeMap, 所以最高整数将在前面,最低和最后,我怎样才能做到这一点?提前谢谢。
答案 0 :(得分:7)
TreeMap
的构造函数可以Comparator
传递自定义实现
更改Map声明以传递逆序比较器
Map<Integer, String> map = new TreeMap<Integer, String>(Collections.reverseOrder());
另见
答案 1 :(得分:2)
怎么样
NavigableMap<Integer, String> map = new TreeMap<Integer, String>();
for(Map<Integer, String> entry : map.descendingMap().entrySet())
System.out.println(entry); // prints key = value