Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TreeMap high-low key Integer sort

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

Output:

  • 1 = One
  • 2 = Two
  • 3 = Three
  • 4 = Four
  • 5 = Five
  • 7 = Seven
  • 8 = Eight
  • 9 = Nine
  • 10 = Ten

I would like to reverse this integer sort of the TreeMap, So the highest integer will be at the front and the lowest and the end, How can I accomplish this? Thanks in advance.

like image 845
user2803086 Avatar asked Jul 24 '14 20:07

user2803086


People also ask

Can TreeMap be sorted by values?

You can't have the TreeMap itself sort on the values, since that defies the SortedMap specification: A Map that further provides a total ordering on its keys. However, using an external collection, you can always sort Map.

Does TreeMap sort by key?

A TreeMap is always sorted based on keys. The sorting order follows the natural ordering of keys. You may also provide a custom Comparator to the TreeMap at the time of creation to let it sort the keys using the supplied Comparator. A TreeMap cannot contain duplicate keys.

Does TreeMap sort the elements using key or value?

In Java Language, a TreeMap always stores key-value pairs which are in sorted order on the basis of the key. TreeMap implements the NavigableMap interface and extends AbstractMap class. TreeMap contains unique keys. The elements in TreeMap are sorted on the basis of keys.

Is TreeMap sorted in ascending order?

By default TreeMap elements in Java are sorted in ascending order of keys. However, we can create the TreeMap in reverse order using Collections. reverseOrder() method in Java and display the elements in descending order of keys.


1 Answers

TreeMap's constructor can take Comparator you can pass custom implementation

Change your Map declaration to pass reverse order comparator

Map<Integer, String> map = new TreeMap<Integer, String>(Collections.reverseOrder());

Also See

  • Sorting a list of points with Java
like image 193
jmj Avatar answered Oct 01 '22 03:10

jmj