I’ve been using a hashmap to store unique words from a text file. Now, I need to compare each word in the hashmap with another larger text file and keep track of the frequency of each word as it appears in the text file.
Whilst adding to the hashmap at first, I only insert the key and set the value to 0. My plan is to use ‘value’ as the frequency of each word in the larger text file.
My attempt is as follows; I first use scanner to read the original file and store the words into the hashmap. Next, I use scanner again, but this time associated with the larger text file. From here on, I’m a bit stuck. I don’t know how to update the ‘value’ and index the ‘key’.
Here is what I have;
Scanner fileScanner = new Scanner (new File (fileName));
fileScanner.useDelimiter (" ");
while (fileScanner.hasNext()) {
for (int i = 0; i < hashmap.size(); i++) { //This I use to index the key field
if (hashmap.get(i).equals(fileScanner.next().toString()) {
int freq ++;
//How do I update the value field of the corresponding value?
}
}
}
Now, obviously, nothing in the above code works, and I’m having some problems with figuring out a way. Could anyone please help me?
If you try to count number of words and store it as map then when new words is added try puting value 1 not 0 (word exist at least once).
For update check if map contains value for key, then put it once again with incremented value. Old value will be replaced.
Try this