views:

175

answers:

1

Ive managed to parse the entire contents of a given input text file and store each word in a hash set. But now i need to find the frequenct of each of these words in this input file, any suggestions as to how I can go about? :)

+1  A: 

Use a HashMap instead of a HashSet and this class as the value:

class Counter {
    public int frequency;
}

addWord() then looks like this:

public void addWord (String word) {
    Counter c = map.get (word);
    if (c == null) {
        c = new Counter ();
        map.put(word, c);
    }
    c.frequency ++;
}
Aaron Digulla
You could just do Map<String, Integer> and avoid the intermediate class.
cletus
Thanks! Now the next problem is how do i print the entire thing.. i need to print each word with its corresponding fruquency..
Nanda
Read the documents on Map?
Jon
for(Entry<String, Integer> e : map) System.out.println(e.getValue + " " + e.getKey())
Thomas Jung
I think il listen to Jon and read through the documents! how different is this from a hashset?
Nanda
You might want to dig out the old comp sci textbook and have a look at the differences between List/Set/Map
leonm
A set is a collection of values, a map is a collection of keys plus one value per key.
Aaron Digulla
Thanks a lot for all the help.. it worked out.. and to print it in a separate file( needed the op in tat form) copied the frequency and the word into 2 separate lists and printing that.. works.. but anything more efficient?
Nanda
@Nanda: Use `for(Map.Entry<String, Integer> entry: map.entrySet()) { System.out.println(entry.getKey()+": "+entry.getValue()+" times"; }`.
Aaron Digulla