Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sorting values in a HashMap

 
Martin Rennix
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
Cheers
Martin
 
Martin Rennix
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whoopee, I've just turned into a ranch hand! :-))
Martin
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Martin,
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
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
Martin
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic