jGuru Forums

vectors with Hashtable - sorting
2 posts in topic
Flat View
TOPIC ACTIONS:

Posted By:   elango_maragtham
Posted On:   Thursday, June 21, 2001 04:18 AM

Hi ..
I am having a vector with say 2 hashtables
inside the hashtable1 i have entries
("rollno","z")
inside the hashtable2 i have entries
("rollno","a")
i want to sort the vector depending on the rollno such that i have second hashtable as first and first hashtable as second .
How can i do this ...

Re: vectors with Hashtable - sorting

Posted By:   Chris_Arnison
Posted On:   Friday, September 21, 2001 07:15 PM

I wanted to do the same thing and came up with the following brute force approach. I could not make sense of the Java collections approach and the Vector of HashMaps, so opted for a quick and dirty ...

`	/**	 *	Sorts a Vector of HashMaps by the specified key field.	 *	Uses the Bubble sort algoritm.	 *	 *	@returns	Returns the modified vector	 */	public static Vector sortVectorHashMap( Vector v, String key, boolean ascending ) {		String key1 = new String();		String key2 = new String();		HashMap hm1 = new HashMap();		HashMap hm2 = new HashMap();		boolean swap = false;		for (int i = v.size(); i >= 0 ; i-- )		{			for (int j = 1; j < v.size(); j++ )			{				hm1 = (HashMap) v.get(j-1);				hm2 = (HashMap) v.get(j);				key1 = (String) hm1.get(key);				key2 = (String) hm2.get(key);				swap = false;				if ( ascending )				{					// If the Ascending flag is set, check for ascending					swap = ( key1.compareTo(key2) > 0  );				}				else				{					// If the Ascending flag is NOT set, check for descending					swap = ( key1.compareTo(key2) < 0  );				}				if ( swap  )				{					// Swap the elements					v.setElementAt( hm1 , j );					v.setElementAt( hm2 , j-1 );				}			}		}		return v;	}`

Re: vectors with Hashtable - sorting

Posted By:   John_Zukowski
Posted On:   Friday, June 22, 2001 07:45 AM

Reading what you say here, it doesn't make sense.

Beyond that, as with any sorting, if you want to define your own mechanism, define a Comparator with your custom sorting implementation.