how To sort a hashmap using its keys and/or values

To sort a hashmap using its keys :-

Dump the HashMap into a TreeMap:

Map yourMap= new HashMap(); // put some tuples in yourMap …
Map sortedMap = new TreeMap(yourMap);

To sort a hashmap using its values :-

public HashMap getSortedMap(HashMap hmap)
HashMap map = new LinkedHashMap();
List mapKeys = new ArrayList(hmap.keySet());
List mapValues = new ArrayList(hmap.values());
TreeSet sortedSet = new TreeSet(mapValues);
Object[] sortedArray = sortedSet.toArray();
int size = sortedArray.length;
// a) Ascending sort

for (int i=0; i<size; i++)

map.put(mapKeys.get(mapValues.indexOf(sortedArray[i])), sortedArray[i]);

return map;

[Java] Reverse ordering a TreeMap

TreeMap is a Map that keep the element in the natural order of the key. The order can be changed providing to the contructor of the TreeMap a Comparable. So you can implement your custom one for more specific tasks. However if you only need a reverse order, you can easily use the beautifulCollections class with his reverseOrder().

Here is a quick example

Map reverseOrderedMap = new TreeMap(Collections.reverseOrder());

Here it is. Easy! :)