Check below code to calculate the frequency of words in a document.
Below I have used a text file having different words or repeating words & using the below I am calculating the frequency of each word & creating the map to get the result.
Below code snippet has been taken from - https://www.staticreference.com/java-8-stream-word-count-example/
Do visit the above website as it has a lot of useful material to look.
In below code I have added the parallelStream also to show the performance improvement.
But do take care while using parallelStream(), as it can improve the performance but can also cause negative impact or even can cause wrong results so do check if your stream can be processed in parallel.
Below I have used a text file having different words or repeating words & using the below I am calculating the frequency of each word & creating the map to get the result.
Below code snippet has been taken from - https://www.staticreference.com/java-8-stream-word-count-example/
Do visit the above website as it has a lot of useful material to look.
In below code I have added the parallelStream also to show the performance improvement.
But do take care while using parallelStream(), as it can improve the performance but can also cause negative impact or even can cause wrong results so do check if your stream can be processed in parallel.
One can look on below code for the sorted result, it works bit slower than without sorting but it is easier to check the results -
Lets look other way to get the frequency or count of each word in the file or in the given list of words.
Below example is assuming that we have a list of words but you can replace that with the stream of words in a file like shown above-
Below example is assuming that we have a list of words but you can replace that with the stream of words in a file like shown above-