Java Reference
In-Depth Information
We can now read the file's contents and store each word that the program encoun-
ters in the map. If we come across a word that we have already seen, we retrieve its
old count value, increment it by 1, and put the new value back into the map. Recall
that when you put a key/value mapping into a map that already contains that key,
the old mapping is replaced. For example, if the word "ocean" was mapped to the
number 25 and we put in a new mapping from "ocean" to 26, the old mapping from
"ocean" to 25 would be replaced; we don't have to remove it manually. Here's the
code to build up the map:
while (in.hasNext()) {
String word = in.next().toLowerCase();
if (wordCountMap.containsKey(word)) { // seen before
int count = wordCountMap.get(word);
wordCountMap.put(word, count + 1);
} else { // never seen before
wordCountMap.put(word, 1);
}
}
Once we've built the word-count map, if we want to print all words that appear
more than, say, 2,000 times in the topic, we can write code like the following:
for (String word : wordCountMap.keySet()) {
int count = wordCountMap.get(word);
if (count > 2000) {
System.out.println(word + " occurs " + count + " times.");
}
}
Here's the complete program, with a method added for structure and a constant
added for the number of occurrences that are needed for a word to be considered
among the most frequent:
1 // Uses maps to implement a word count, so that the user
2 // can see which words occur the most in the topic Moby-Dick.
3
4 import java.io.*;
5 import java.util.*;
6
7 public class WordCount {
8
// minimum number of occurrences needed to be printed
Search WWH ::




Custom Search