File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Hashtable sort by key Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Hashtable sort by key" Watch "Hashtable sort by key" New topic

Hashtable sort by key

mickey hendrix

Joined: May 08, 2005
Posts: 19
hello to everybody
I have a problem sorting an Hashtable by the key:this is a String like an ip like "" and the object is generic...anything:

Hashtable hash = new Hashtable;

Now that I have valorized the items I need to order the hashtable in ascending mode by the key....
How can I do?Ot I have to use another Struct ( like Set or Map ) in witch put the data?
thanks for help
Paul Clapham

Joined: Oct 14, 2005
Posts: 19973

TreeMap is a sorted Map. From its API documentation:

"This class guarantees that the map will be in ascending key order, sorted according to the natural order for the key's class (see Comparable)"

The keys need to implement Comparable, so since your keys are Strings, they do that. No problem there.
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
Yes, you could have used TreeMap from the get-go. Or you could copy your
hashtable into a TreeMap if other code is providing the hash table

And if you are stuck with a hash table, but all you need to do is iterate
through it, copy the keys into an array and sort it:

There is no emoticon for what I am feeling!
I agree. Here's the link:
subject: Hashtable sort by key
It's not a secret anymore!