Forums Register Login

Sorting values in a HashMap

+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
Whoopee, I've just turned into a ranch hand! :-))
Martin
+Pie Number of slices to send: Send
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).]
+Pie Number of slices to send: Send
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
Every plan is a little cooler if you have a blimp. And a tiny ad.
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 1413 times.
Similar Threads
If two different objects have same hashcode, how HashMap will retrieve these two objects?
HashMap and Vector
Multiple set of data mapping
My head is about to explode!
Make HashMap elements fit into an ArrayList
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 18, 2024 21:01:29.