TreeMap高低键整数排序

时间:2014-07-24 20:26:47

标签: java sorting integer treemap

    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);
    }

输出:

  • 1 =一个
  • 2 =两个
  • 3 =三
  • 4 =四
  • 5 =五
  • 7 =七
  • 8 =八
  • 9 =九
  • 10 =十

我想反转这种整数种类的TreeMap, 所以最高整数将在前面,最低和最后,我怎样才能做到这一点?提前谢谢。

2 个答案:

答案 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