Count Number Of Occurrences Of A Word In A Text File In Java
In this tutorial, we are going to figure out how many times a word is repeated in the text file using a map interface method through a Java program. If you don’t know how to count the number of occurrences of a word in a text file using a hash-map then you are at the right place to know your problem’s solution.
You may learn: Reading A Text File Line By Line In Java With Example
How to Count Number Of Occurrences Of A Word In A Text File In Java
The first thing you need to do is grab a text file in which you have to perform the operation of counting the word occurrences example I have a file named “shubham.txt” in which I will be counting the occurrences of each word.
Suppose in “shubham.txt” the content is-
Hello my name is shubham kumar raj and, i am persuing my graduation from UPES Dehradun i am a final year student.
Map Interface in Java:-
The java.util.Map interface speaks to a mapping between a key and a value. Consequently, it acts somewhat unique in relation to the remainder of the gathering types. You can learn: Working with HashMap (Insertion, Deletion, Iteration) in Java
The following java code will help you to achieve your solution:-
import java.util.Map; import java.util.Scanner; public class CountEachWords { void CountWords(String filename, Map< String, Integer> words) throws FileNotFoundException { Scanner file=new Scanner (new File(filename)); while(file.hasNext()){ String word=file.next(); Integer count=words.get(word); if(count!=null) count++; else count=1; words.put(word,count); } file.close(); } public static void main(String[] args) { Map<String,Integer> words=new HashMap<String, Integer>(); CountWords("shubham.txt",words); System.out.println(words); } }
The given below will be the output of the following code:-
Hello=1, my=2, name=1, is=1, shubham=1, kumar=1, raj=1, and=1, i=2, am=2, persuing=1, graduation=1, from=1, UPES=1, Dehradun=1, a=1, final=1, year=1, student=1.
This is how we can count the number of occurrences of a word in a text (.txt) file in Java.
Also read:
Leave a Reply