Reputation: 21
I'm trying to count the frequency of words in a TreeMap
. I'm reading a file and passing the lines to a StringTokenizer
and converting it afterwards to a string word by word (currentword).
If currentword = "one"
then it puts it on the map, but if the second word is one
again instead of fetching frequency
= 1 it gets null
again!
final StringTokenizer parser = new StringTokenizer(currentLine, " \0\t\n\r\f.,;:!?'");
while (parser.hasMoreTokens()) {
String currentWord = parser.nextToken();
Integer frequency = frequencyMap.get(currentWord);
if (frequency == null) {
frequency = 0;
}
frequency++;
frequencyMap.put(currentWord, frequency);
}
Upvotes: 2
Views: 239
Reputation: 1500485
Looks like it works fine to me:
import java.util.*;
public class Test
{
public static void main(String[] args) {
Map<String, Integer> map = new TreeMap<String, Integer>();
String[] words = { "x", "one", "y", "one" };
for (String word : words) {
Integer frequency = map.get(word);
if (frequency == null) {
frequency = 0;
}
frequency++;
map.put(word, frequency);
}
System.out.println(map);
}
}
Output:
{one=2, x=1, y=1}
See if you can come up with a similar short but complete program which demonstrates your problem - possibly by gradually cutting down your "real" code to something similar.
Upvotes: 3