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

About lorddisk

WebCenter Content, WebCenter Portal, WebCenter Sites,Weblogic, Identity and Access Management (IAM),SSO,OAM,OIM,OAAM,OUD, OPAM,OID, OVD ,Oracle API Gateway ,OBIEE,OEDQ, Oracle ADF, Oracle SOA,J2EE, CackePHP ,PHP,J2SE,J2EE,Spring,Hibernate,JQuery,CSS,Java Script ,Joomla,Drupal,Worpress
This entry was posted in collections. Bookmark the permalink.