Sorting hashtable entries

i need to sort hashtable entries according to the values (objects).

eg. i have hash table as follows:

keyvalue

cat2

dog5

cow5

mouse1

value represents a class containing 'int'. i need to sort according to this integer value and get a hashtable as follows

keyvalue

dog5

cow5

cat2

mouse1

or just get keys as an array (or vector) as

dog

cow

cat

mouse

thanks

[471 byte] By [tomcla] at [2007-9-27 11:55:13]
# 1
Instead of using a Hashtable, consider using a SortedMap like TreeMap. See the API docs for more information.
rhasselbauma at 2007-7-9 6:47:25 > top of Java-index,Archived Forums,Java Programming...
# 2
thanks but i should sort not on keys but on the values of the object in it. or i am wrong and i can do it with treemap as well?
tomcla at 2007-7-9 6:47:25 > top of Java-index,Archived Forums,Java Programming...
# 3
TreeMap will not sort values. So you can either populate it with the keys and values reversed, or if you only care about getting a sorted list of the integers, you could use a TreeSet.
rhasselbauma at 2007-7-9 6:47:25 > top of Java-index,Archived Forums,Java Programming...
# 4

> TreeMap will not sort values. So you can either

> populate it with the keys and values reversed

This won't work if the values are not unique.

If you just need a sorted list of the values you can do this:

ArrayList values = new ArrayList(new hashtable.values()); //use HashMap instead

Collections.sort(values);

The problem is, if you need the keys in this order you will have to relate them back to the keys, which can be slow. Is that what you need to do?

dubwaia at 2007-7-9 6:47:25 > top of Java-index,Archived Forums,Java Programming...
# 5
yes i need to get the keys back. also the integers in values can be similar. i will try anyway. thanks a lot
tomcla at 2007-7-9 6:47:25 > top of Java-index,Archived Forums,Java Programming...