aspose file tools*
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


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Hashtable sort by key" Watch "Hashtable sort by key" New topic
Author

Hashtable sort by key

mickey hendrix
Greenhorn

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 "120.3.5.3" and the object is generic...anything:
Example:

Hashtable hash = new Hashtable;
hash.put("12.5.8.10",myObject);
hash.put("12.7.8.10",myObject);
hash.put("12.5.9.10",myObject);
hash.put("12.24.8.10",myObject);
hash.put("12.5.8.11",myObject);

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
Bartender

Joined: Oct 14, 2005
Posts: 18657
    
    8

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: http://aspose.com/file-tools
 
subject: Hashtable sort by key