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);
}
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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With