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