Java Program to Find the Most Repeated Word in a Text File Last Updated : 20 Feb, 2023 Comments Improve Suggest changes Like Article Like Report Map and Map.Entry interface will be used as the Map interface maps unique keys to values. A key is an object that is used to retrieve a value at a later date. The Map.Entry interface enables you to work with a map entry. Also, we will use the HashMap class to store items in "key/value” pairs and access them by an index of another type. Illustration: Suppose the content of the sample text file is as follows: Input: A text file containing sequence of arbitrary words “How to count the number of occurrence of each word? How to count number or each word in string. Calculating frequency of each word in a sentence in java.” Output: List of words that have the maximum occurrence in = 3 each = 3 of = 3 to = 3 Implementation: Sample file input image is as follows: Example Java // Java Program to Find the // Most Repeated Word in a Text File // Importing File classes import java.io.File; import java.io.FileNotFoundException; // Importing Map and HashMap class from // java.util package import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; // Importing Scanner class to // take input from the user import java.util.Scanner; // Class // To find maximum occurrences public class GFG { // Method 1 - getWords() // Reading out words from the file and // mapping key value pair corresponding to // each different word static void getWords(String fileName, Map<String, Integer> words) throws FileNotFoundException { // Creating a Scanner class object Scanner file = new Scanner(new File(fileName)); // Condition check using hasNext() method which // holds true till there is word being read from the // file. // As the end of file content,condition violates while (file.hasNext()) { // Reading word using next() method String word = file.next(); // Frequency count variable Integer count = words.get(word); // If the same word is repeating if (count != null) { // Incrementing corresponding count by unity // every time it repeats // while reading from the file count++; } else // If word never occurred after occurring // once, set count as unity count = 1; words.put(word, count); } // Close the file and free up the resources file.close(); } // Method 2 - getMaxOccurrence() // To get maximum occurred Word static int getMaxOccurrence(Map<String, Integer> words) { // Initially set maximum count as unity int max = 1; // Iterating over above Map using for-each loop for (Entry<String, Integer> word : words.entrySet()) { // Condition check // Update current max value with the value // exceeding unity in Map while traversing if (word.getValue() > max) { max = word.getValue(); } } // Return the maximum value from the Map return max; } // Method 3 // Main driver method public static void main(String[] args) throws FileNotFoundException { // Creating an object of type Map // Declaring object of String and Integer types Map<String, Integer> words = new HashMap<String, Integer>(); // Retrieving the path as parameter to Method1() // above to get the file to be read getWords("C:\\Users\\dell\\sample.txt", words); // Variable holding the maximum // repeated word count in a file int max = getMaxOccurrence(words); // Traversing using for each loop // Creating a set out of same elements // contained in a HashMap for (Entry<String, Integer> word : words.entrySet()) { // Comparing values using geValue() method if (word.getValue() == max) { // Print and display word-count pair System.out.println(word); } } } Output: Time Complexity: O(n)Auxiliary Space: O(n) Comment More infoAdvertise with us Next Article Java Program to Find the Most Repeated Word in a Text File P pawki Follow Improve Article Tags : Java Technical Scripter Java Programs Technical Scripter 2020 Java-Files +1 More Practice Tags : Java Similar Reads Java Program to Print All the Repeated Numbers with Frequency in an Array The frequency of an element in an array is the count of the occurrence of that particular element in the whole array. Given an array that may contain duplicates, print all repeated/duplicate elements and their frequencies. Below is the discussion of this program by two approaches: Using a counter ar 4 min read Java Program to Find Duplicate Words in a Regular Expression Given an Expression which is represented by String. The task is to find duplicate elements in a Regular Expression in Java. Use a map or set data structures for identifying the uniqueness of words in a sentence. Examples: Input : str = " Hi, I am Hritik and I am a programmer. " Output: I am Explanat 3 min read Java Program To Find Length Of The Longest Substring Without Repeating Characters Given a string str, find the length of the longest substring without repeating characters. For âABDEFGABEFâ, the longest substring are âBDEFGAâ and "DEFGAB", with length 6.For âBBBBâ the longest substring is âBâ, with length 1.For "GEEKSFORGEEKS", there are two longest substrings shown in the below 8 min read Java Program to Find Occurrence of a Word Using Regex Java's regular expressions, or regex, let you do advanced text manipulation and matching. Regex offers a handy approach for searching for a term in a text wherever it appears. In this article, we will learn to find every occurrence of a word using regex. Program to Find Occurrence of a Word Using Re 2 min read Java Program to Find the Occurrence of Words in a String using HashMap HashMap<Key, Value> provides the basic implementation of the Map interface of Java and import java.util.HashMap package or its superclass. HashMap stores the data in (Key, Value) pairs, and accessed by an index of another type (e.g. an Integer). One object is used as a key to another object. I 3 min read Java Program to Search a Particular Word in a String Using Regex In Java string manipulation, searching for specific words is a fundamental task. Regular expressions (regex) offer a powerful and flexible approach to achieve this search. It matches the patterns simply by comparing substrings. In this article, we will learn how to search for a particular word in a 3 min read Java Program to Print all Unique Words of a String Java program to print all unique words present in the string. The task is to print all words occurring only once in the string. Illustration: Input : Welcome to Geeks for Geeks. Output : Welcome to for Input : Java is great.Python is also great. Output : Java Python also Methods: This can be done in 4 min read Java Program to Implement the String Search Algorithm for Short Text Sizes Pattern searching is a crucial problem in computer science. When we do search for a string in notepad/word file or browser or database, pattern searching algorithms are used to show the search results. A typical problem statement would be-Given a text txt[0..n-1] and a pattern pat[0..m-1], write a f 4 min read Java Program To Find Longest Common Prefix Using Sorting Problem Statement: Given a set of strings, find the longest common prefix.Examples: Input: {"geeksforgeeks", "geeks", "geek", "geezer"} Output: "gee" Input: {"apple", "ape", "april"} Output: "ap" The longest common prefix for an array of strings is the common prefix between 2 most dissimilar strings 2 min read Java program to print all duplicate characters in a string Given a string, the task is to write Java program to print all the duplicate characters with their frequency Example: Input: str = "geeksforgeeks" Output: s : 2 e : 4 g : 2 k : 2 Input: str = "java" Output: a : 2 Approach: The idea is to do hashing using HashMap. Create a hashMap of type {char, int} 2 min read Like