How can I sort a ENTIRE PAIR key/value, sort by the value, in a Hashtable?
3 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Anonymous
Posted On:   Wednesday, April 4, 2001 08:12 AM

I have more JSP's with combo-box, with the values of the keys and the names of the values of a Hashtable. I need a Hashtable with their pairs sortered by the value, not by the key. Any idea?

Re: How can I sort a ENTIRE PAIR key/value, sort by the value, in a Hashtable?

Posted By:   Anonymous  
Posted On:   Sunday, April 22, 2001 10:48 PM

Hi,
If i understand correctly u wanna, sort elements in the hastable (for eg:-if u have state combo box, u wanna sort it alphabetically).
If ur using a hashtable the only solution which i suggest is something like this...
Hashtable has a method ketSet, which returns a Set interface. Set interface has a method toArray which returns a Object array. Pass this object array to a method in Arrays.sort(Object o[]). Ur keys get sorted. Now get the values from the hashtable which gets sorted automatically.....

This is a round about method....-:)

Re: How can I sort a ENTIRE PAIR key/value, sort by the value, in a Hashtable?

Posted By:   AlessandroA_Garbagnati  
Posted On:   Wednesday, April 4, 2001 10:16 AM

Nestor,

I think that the best and cleanes way to achieve that is using a java.util.TreeMap instead of a java.util.Hashtable (they both implements java.util.Map).

Then, you create your own java.util.Comparator that sorts the elements based on your specific needs. You create a TreeMap using that Comparator (it's one of the contructor) and that's it. Every time you'll insert a new key/pair, it will be sorted in the map.

Re: How can I sort a ENTIRE PAIR key/value, sort by the value, in a Hashtable?

Posted By:   Christopher_Schultz  
Posted On:   Wednesday, April 4, 2001 09:03 AM

If you mean that you want to be able to get a value's key based only on it's value, then you need to do one of two things:




  1. Loop through all of the keys in the hashtable, get the value for each key, and compare it to your test value. If it is equal, then you've found the key for your value.
  2. Create another Hashtable and perform a key/value inversion, where you basically perform #1 above, but store the results in a second hashtable, keyed on the values of the other table.


If you are going to have a lot of lookups, but very few changes to the structure, then #2 is probably the way to go. On the other hand, if you are going to be doing lots of put()s and not keeping the other hashtable up to date, then the looping method of #1 might be the right answer.



-chris
About | Sitemap | Contact