Mr. Ram
05-31-2006, 11:01 PM
How to sort a hashmap using its keys and/or values
|
Click to See Complete Forum and Search --> : To sort a hashmap using its keys and/or values Mr. Ram 05-31-2006, 11:01 PM How to sort a hashmap using its keys and/or values Waylander 06-01-2006, 02:35 AM Why do you want to sort the list? a Hashmap is a key pair system, your supposed to use the key to get the value... thats why its called a key. If you need something to be sorted then I would recommend using an object that is sorted, like an ArrayList. What is it your storing in the map? is it a result set or something? Waylander. Mr. Ram 06-01-2006, 11:55 PM 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; } webdeveloper.com
Copyright Internet.com Inc., All Rights Reserved. |