dcsimg
Sorting of values in Hashtable
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Mahesh_B
Posted On:   Wednesday, May 30, 2001 01:14 PM

Is there any way by which the values in
a hashtable can be sorted in Java 1.1.
I am using Java 1.1 and before displaying the products in a template I am retrieving the values(product names) from the hashtable. I want the products to be displayed in a sorted order.

Re: Sorting of values in Hashtable

Posted By:   Jonathan_Downey  
Posted On:   Tuesday, February 12, 2002 09:41 AM

I had the same problem, and I needed to use a Hashtable because it was Serialable. So when I wanted to display the sorted list I used the following code. Assume data is the HashTable:

TreeMap sorted = new TreeMap( new SimpleComparator() );
sorted.putAll(data);
Iterator it = sorted.keySet().iterator();
while(it.hasNext() ) {
String curName = (String)it.next();
String curVal = (String)data.get(curName);
// Do whatever you want after this
}


The SimpleComparator basically sorts the keys as Floats, in my case.

import java.util.Comparator;
import java.io.*;

public class SimpleComparator implements Comparator{

public int compare(Object o1, Object o2) throws ClassCastException {
String v1 = (String)o1, v2 = (String)o2;
try {
float f1 = Float.parseFloat(v1);
float f2 = Float.parseFloat(v2);

if(f1 == f2) return 0;
else if(f1 > f2) return 1;
else return -1;
} catch(Exception ex) {}
return v1.compareTo(v2);
}
}

And that outputs a sorted Hashtable. Of course, if the Hashtable is huge and you don't need Serializable, you can use a TreeMap from the start, to avoid the creation overhead of making a huge TreeMap every time you want to display.


Jonathan

Re: Sorting of values in Hashtable

Posted By:   John_Zukowski  
Posted On:   Wednesday, May 30, 2001 09:02 PM

Essentially not, especially since the values are stored by their key, so even in 1.2 with the collections framework you can't. Once you retrieve them all, you can sort them yourself before displaying. That's about all you can do.
About | Sitemap | Contact