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
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