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...

  1. Create a method that takes a String array. The array contains all the words in a string:
            public void getFreqStats(String[] words){ 
    
  2. Create a Frequency class object:
            Frequency freq = new Frequency(); 
    
  3. Add all the words to the Frequency object:
            for( int i = 0; i < words.length; i++) { 
              freq.addValue(words[i].trim()); 
            } 
    
  4. For each word, count the frequency using the Frequency class's getCount() method. Finally, ...

Get Java Data Science Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.