Originally you just wanted to get a
consistent order, not necessarily sorted. For that, I would recommend a LinkedHashMap, which will (by default) order the elements in the order they were inserted into the Map. Its performance for most operations is O(1), slower than HashMap but faster than TreeMap.
Now if you really want the entries sorted by
value, using a custom Comparator in a single TreeMap fundamentally will not work. The Comparator is used to compare
keys, and determine (among other things) if they're equal. If you try to use the comparator to compare values instead, the comparator will fail to detect equal keys, and the Map will become useless as you will be unable to retrieve a value using a key. The fact that you got ClassCastException probably indicates your Comparator was confused about whether it had a key or value. But fundamentally, there's no way to fix this within a single TreeMap.
I'm not sure I want to know what it means to "sort a Hashtable". But if it's working for you, good.
If each value is unique, I would probably use a second TreeMap in which the key and value are swapped. Or check out
TreeBidiMap and
DualTreeBidiMap from Jakarta Commons. If the values are
not unique, then I'd do something like this:
Is that what you meant by sorting the Hashtable?