Counting word frequency in a string
This recipe is quite different than the other recipes in this chapter as it deals with strings and counting word frequencies in a string. We will use both Apache Commons Math and Java 8 for this task. This recipe will use the external library while the next recipe will achieve the same with Java 8.
How to do it...
Create a method that takes a
Stringarray. The array contains all the words in a string:public void getFreqStats(String[] words){Create a
Frequencyclass object:Frequency freq = new Frequency();
Add all the words to the
Frequencyobject:for( int i = 0; i < words.length; i++) { freq.addValue(words[i].trim()); }For each word, count the frequency using the
Frequencyclass'sgetCount()method. Finally, after processing the frequencies, close the method:
for( int i = 0; i < words.length; i++) {
System.out.println(words[i] + "=" +
...