Sorting a hashtable

F

Frank

Craig said:
What's the best way to sort a java.util.Hashtable which contains Comparable
objects?

To sort by keys you use a TreeMap (Use HashMap over Hashtable, btw..),
to sort the values you need to place them in a container that is/can be
sorted (List / TreeSet / array / whatever).
 
D

Doni Ocena

Try this:

i) get a collection of values by calling values() on your hashtable
ii) call toArray() on your collection from step (i)
iii) use Arrays.sort() on your array from step(ii)

Regards,
Doni
 
T

Thomas Weidenfeller

Craig said:
What's the best way to sort a java.util.Hashtable which contains Comparable
objects?


"best" in what sense? Least amount of code to write?

But first, a hashtable can't be sorted. It is a data structure which
maps keys to values, and because of the used algorithm (hashing),
always keeps the elements in the order of the hashes of the keys (with
gaps in between).

You must copy the elements to some other data structure. You can e.g.
extract either the keys or values so you can sort them separately.
Since you didn't specify if you want the keys or values sorted, I will
assume you want the keys sorted. In this case, however, the "best" (in
the sense of least code to write) would be to copy the whole hashtable
to a TreeMap:

TreeMap tm = new TreeMap(yourHashtable);
SortedSet sortedEntries = (SortedSet)tm.entrySet();

/Thomas
 
J

John C. Bollinger

Craig said:
What's the best way to sort a java.util.Hashtable which contains Comparable
objects?

You cannot sort a Hashtable (what would it even mean?), but you can
extract its values and sort them. For example:

public List sortedMapValues(Map map) { // a Hashtable is a Map
List rval = new ArrayList(map.values());

Collections.sort(rval); // assumes mutually Comparable values
return rval;
}

You can do other, similar things with the key set and entry set.

If you want a Map that always maintains its elements in order by key,
then you want a SortedMap, such as a TreeMap. You could probably
manipulate a LinkedHashMap in such a way as to cause its entry iteration
order to match some sorting scheme, but that would be way more trouble
than it was worth.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top