I am building a basic word frequency counter. The code is listed below:
public static List<Frequency> computeWordFrequencies(List<String> words)
{
List<Frequency> list_of_frequency = new ArrayList<Frequency>();
List<String> list_of_words = words;
int j = 0;
for(int i=0; i<list_of_words.size(); i++)
{
String current_word = list_of_words.get(i);
boolean added = false;
if(list_of_frequency.size() == 0)
{
list_of_frequency.add(new Frequency(current_word, 1));
System.out.println("added " + current_word);
}
else
{
System.out.println("Current word: " + current_word);
System.out.println("Current Frequency: " + list_of_frequency.get(j).getText());
if(list_of_frequency.contains(current_word))
{
list_of_frequency.get(j).incrementFrequency();
System.out.println("found... incremented " + list_of_frequency.get(j).getText() + " frequency");
added = true;
}
else
{
list_of_frequency.add(new Frequency(current_word, 1));
System.out.println("added " + current_word);
added = true;
}
}
}
}
and the output I am getting is:
added I
Current word: am
Current Frequency: I
added am
Current word: very
Current Frequency: I
added very
Current word: good
Current Frequency: I
added good
Current word: at
Current Frequency: I
added at
Current word: being
Current Frequency: I
added being
Current word: good
Current Frequency: I
added good
Total item count: 7
Unique item count: 7
I:1
am:1
very:1
good:1
at:1
being:1
good:1
So I need a for loop to loop through the “list_of_frequency” but if I do that I run into other problems such as adding words repetitively. Is my logic right here and would there be a better way going about this project?
Thanks in advance!
you can do this using frequency method of
Collectionsclasshere is a sample: