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
2009-12-07 09:15:12
You could just do Map<String, Integer> and avoid the intermediate class.
cletus
2009-12-07 09:17:59
Thanks! Now the next problem is how do i print the entire thing.. i need to print each word with its corresponding fruquency..
Nanda
2009-12-07 09:23:24
Read the documents on Map?
Jon
2009-12-07 09:25:32
for(Entry<String, Integer> e : map) System.out.println(e.getValue + " " + e.getKey())
Thomas Jung
2009-12-07 09:26:57
I think il listen to Jon and read through the documents! how different is this from a hashset?
Nanda
2009-12-07 09:28:39
You might want to dig out the old comp sci textbook and have a look at the differences between List/Set/Map
leonm
2009-12-07 09:34:25
A set is a collection of values, a map is a collection of keys plus one value per key.
Aaron Digulla
2009-12-07 13:30:41
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
2009-12-08 03:33:16
@Nanda: Use `for(Map.Entry<String, Integer> entry: map.entrySet()) { System.out.println(entry.getKey()+": "+entry.getValue()+" times"; }`.
Aaron Digulla
2009-12-08 09:23:48