How to Find Most Occurred Word in a File in Java

a-java-program-to-find-most-occured-word-in-a-file

Hey, welcome to The Practice House. In this post, we are going to learn about a question that you will face in almost every java interview questions. The Question is How to Find Most Occurred Word in a File.

So Let’s Learn How to Find Most Occurred Word in a File.

Small Explanation: I know we like to see the code and we love to understand by ourselves. It’s great I also do the same so explanation part for them those are facing difficulty to understand the below program. Feel Free to Skip this part and scroll down Straight to the code and sample output.

So, let’s talk about the problem first. Let’s say we have a huge file and we need to tell our manager that inside this text file what words appeared how many times or about all the words how many times they appeared.

So our TO-DO list will be :

  • Read the file
  • Get the word
  • Count the number of times it’s appeared
  • Output it’s for our Manager

So to encounter above TO-DO list we already know that there is a lot of ways to do these things but I will keep it simple here you can use any method that you like. We will use FileReader from java.io.FileReader  to read our file.

Now we will use Scanner from java.util.Scanner to read from this file.

Now the best way to store our word and the counts are HashMap from java.util.HashMap. Inside our HashMap we will store our word as Key and The Counts as a Value.

Then we will use Collections.max(yourHashMap.values()) to get the max values from our Map. This is the most occurred word in your file.

After this, I also loop through our map to get all the values that which word is occurred in how many times.

Clone the Sample Project from GitHub :  Download / Clone Sample Project

Sample File:

Sample Code:

Sample Output:

 

Thank you so much for reading this post. If you have any questions and comments please write a destructive comment below. I will love to answer your questions.

Leave a Reply

avatar
  Subscribe  
Notify of