Wrox Programmer Forums
Go Back   Wrox Programmer Forums > Java > Java and JDK > Java Basics
|
Java Basics General beginning Java language questions that don't fit in one of the more specific forums. Please specify what version.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the Java Basics section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old May 31st, 2006, 10:20 PM
Authorized User
 
Join Date: Mar 2006
Posts: 40
Thanks: 0
Thanked 0 Times in 0 Posts
Default To sort a hashmap using its keys and/or values

How to sort a hashmap using its keys and/or values...?

 
Old June 1st, 2006, 11:19 PM
Authorized User
 
Join Date: Mar 2006
Posts: 40
Thanks: 0
Thanked 0 Times in 0 Posts
Default

[u]To sort a hashmap using its keys</u> :-

Dump the HashMap into a TreeMap:

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


[u]To sort a hashmap using its values</u> :-

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;
}





Similar Threads
Thread Thread Starter Forum Replies Last Post
Forcing blank values to bottom of a sort jpullam XSLT 3 August 11th, 2008 03:36 PM
Insert database values into a Hashmap collection xaitienle Struts 1 June 19th, 2006 06:04 AM
how to sort cross tab.sort based on row total joxa83 Crystal Reports 7 March 2nd, 2006 09:12 AM
When to define primary keys and foregin keys? method SQL Server 2000 1 August 26th, 2005 09:14 AM
HashMap freezotic BOOK: Beginning Java 2 6 March 26th, 2004 04:27 PM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.