How to sort based on hash values?

R

Ramon F Herrera

I have an application which counts word frequency.
As I scan every word, its subtotal is placed in a
hash, as exemplified by this Perl pseudo code:

Frequency{"this"}++
Frequency{"that"}++
Frequency{"whatever"}++

When the counting loop is done, I would like to find out
which words are the most common ones. So what I need is
to perform a sort based on the hash values, considering
them as integers.

How can I do that?

TIA,

-Ramon F Herrera
 
J

John C. Bollinger

Ramon said:
I have an application which counts word frequency.
As I scan every word, its subtotal is placed in a
hash, as exemplified by this Perl pseudo code:

Frequency{"this"}++
Frequency{"that"}++
Frequency{"whatever"}++

When the counting loop is done, I would like to find out
which words are the most common ones. So what I need is
to perform a sort based on the hash values, considering
them as integers.

How can I do that?

Supposing that for a data structure you are using HashMap, you would do
something like this:

List results = new ArrayList(hash.entrySet());
Collections.sort(results, new MyResultComparator());

where MyResultComparator is a Comparator implementation you write that
will sort the list of results the way you want (where each element of
results is an object implementing Map.Entry). If the values in the map
contain enough information, then you might instead dump them to the list
(see Map.values()) and sort them directly.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,153
Members
46,701
Latest member
XavierQ83

Latest Threads

Top