• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Sorting values in a HashMap

 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Whoopee, I've just turned into a ranch hand! :-))
Martin
 
author
Posts: 3252
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
reply
    Bookmark Topic Watch Topic
  • New Topic