This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes Sorting values in a HashMap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Sorting values in a HashMap" Watch "Sorting values in a HashMap" New topic

Sorting values in a HashMap

Martin Rennix
Ranch Hand

Joined: Sep 30, 2001
Posts: 34
Hi all,
I've got a letter frequency table stored in a HashMap, that stores the frequency that each letter appears in a text file. Basically the keys are letters and the values are the frequency.
Now, I want to display the key/value pairs sorted in descending order based on the value, not the key. My initial thought is:
1. Call HashMap.entrySet() to get the key/value pairs as a Set.
2. Call Set.toArray() to convert the Set to an array.
3. Define a class that implements Comparator and define a compare method that compares values (frequency)
4. Call Arrays.sort(Object[], MyComparator) to sort my array of key/value pairs.
It seems complicated but at least I don't have to write my own sorting routine! Does anyone else have a simpler method?
Martin Rennix
Ranch Hand

Joined: Sep 30, 2001
Posts: 34
Whoopee, I've just turned into a ranch hand! :-))
Peter den Haan
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
Congratulations on your promotion
You're close - and it isn't nearly as complicated as it looks. But skip the Array. Instead, use your Comparator to create a proper sorted set: All that needs doing really is the comparator.
- Peter

[This message has been edited by Peter den Haan (edited October 25, 2001).]
Martin Rennix
Ranch Hand

Joined: Sep 30, 2001
Posts: 34
Thanks Peter, that's really very neat. I forgot you could construct a TreeSet with a Comparator. The collection classes are very powerful aren't they!
I agree. Here's the link:
subject: Sorting values in a HashMap
Similar Threads
Make HashMap elements fit into an ArrayList
HashMap and Vector
If two different objects have same hashcode, how HashMap will retrieve these two objects?
Multiple set of data mapping
My head is about to explode!