collections

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());
hmap.clear();
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;
}

Advertisements