• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

Question about Sorting with Hashtable

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi

I want to sort a Hashtable's values in alphabetical,with duplicates and in case_insensitive manner. I tried the following code. Please take a look.



With the above code I got the values in the Hashtable alphabetically,with duplicates and in case_insensitive manner. Now I want to have corresponding keys also. How to do this?

Any help is appreciated.

Thanks
Manimekala
 
Ranch Hand
Posts: 1970
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sounds like you want a SortedMap, not a Hashtable (*). There is an implementation of SortedMap in the API; look up TreeMap.

(*) Note that you almost never actually want a Hashtable. That's an old, obsolete class. Where you might have used Hashtable, you should generally use HashMap.
 
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If I understand the OP correctly, he wants the keys in the order specified by the sorted values. If that's right, then a SortedMap won't work, as that is sorted by the keys.

As Peter says, it is better to use a HashMap. You can retrieve a set of Map.Entry objects from this using the entrySet method. These objects contain the key and value. You will then need to write a Comparator to sort these and pass an instance of this Comparator to the Collections.sort method.

Your Comparator will be pretty simple. In the overridden compare method, simply use the Map.Entry.getValue method to retrieve the values and compare them using the String.compareToIgnoreCase method.

Of course, if Peter's interpretation of your question was correct, just ignore this post.
 
The airline is called "Virgin"? Don't you want a plane to go all the way? This tiny ad will go all the way:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic