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
String
array. The array contains all the words in a string:public void getFreqStats(String[] words){
Create a
Frequency
class object:Frequency freq = new Frequency();
Add all the words to the
Frequency
object:for( int i = 0; i < words.length; i++) { freq.addValue(words[i].trim()); }
For each word, count the frequency using the
Frequency
class'sgetCount()
method. Finally, after processing the frequencies, close the method:
for( int i = 0; i < words.length; i++) { System.out.println(words[i] + "=" + ...