This recipe does not use the Apache Commons Math library to count frequencies of words in a given string; rather it uses core libraries and mechanisms introduced in Java 8.
Note
There are many ways to implement a working example that counts word frequencies, and therefore, the readers are encouraged to look at many implementations of this recipe in Java versions released earlier than 8.
Create a method that takes a string argument. We will be counting frequencies of the words in this string:
public void getFreqStats(String str){
Create a
Stream
from the given string. In our case, we will be converting the string to lower case and identify words based on a regular expression\W+
. The process of converting a string into a stream will be done in parallel:Stream<String> stream = Stream.of(str.toLowerCase().split("\\W+")).parallel();
We will be collecting the words and their frequencies...