logo
  • Programming
  • Testing
  • AI
  • Devops
  • Data Science
  • Design
  • Blogs
  • Crypto Tools
  • Dev Feed
  • Login
Story
Follow @devglan

Java program to find max repeated words from a file

author-image   By Dhiraj Ray,   01 January, 2018 10K

Description

In java interview, this program can be asked in a multiple ways such as write program to find max repeated words or duplicate words or the count of each duplicate words.Whatever the question, the main programming concept is the same to count the occurrence of each word in a .txt file. To solve this programatically, we can use Map implmenetation in Java that does not allow any duplicate key and at the end of iteration we can find out the count.Following is the complete program.Here, we are using java 8 Lambda operator during sorting.

MaxRepeatedWord.java
package com.devglan;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Map.Entry;

public class MaxRepeatedWord {

    public Map getWordsCount(String fileName){

        FileInputStream fis;
        DataInputStream dis;
        BufferedReader br = null;
        Map wordMap = new HashMap();
        try {
            fis = new FileInputStream(fileName);
            dis = new DataInputStream(fis);
            br = new BufferedReader(new InputStreamReader(dis));
            String line;
            while((line = br.readLine()) != null){
                StringTokenizer st = new StringTokenizer(line, " ");
                while(st.hasMoreTokens()){
                    String tmp = st.nextToken().toLowerCase();
                    if(wordMap.containsKey(tmp)){
                        wordMap.put(tmp, wordMap.get(tmp)+1);
                    } else {
                        wordMap.put(tmp, 1);
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            try {
                if (br != null) {
                    br.close();
                }
            } catch(Exception ex){

            }
        }
        return wordMap;
    }

    public List> sortByValue(Map wordMap){

        Set> set = wordMap.entrySet();
        List> list = new ArrayList>(set);
        Collections.sort(list, (o1, o2) -> (o2.getValue()).compareTo( o1.getValue() ));
        return list;
    }

    public static void main(String a[]){
        MaxRepeatedWord maxRepeatedWord = new MaxRepeatedWord();
        Map wordMap = maxRepeatedWord.getWordsCount("C:/test.txt");
        List> list = maxRepeatedWord.sortByValue(wordMap);
        System.out.println("Max repeated word is " + list.get(0).getKey() + " with count - " + list.get(0).getValue());
    }
}

Explanation

Click to Suggest Your Own Explanation

Tokenize each line into words and put into a Map.If the map already contains the key, incrase the count else make the count as 1.At the end, sort it based on value in descending order so that the max repeated word will be on top.

Other Similar Java Programs:

1 Java Program to test if given number is Armstrong or not
2 Java Program to test if a given number is Fibonacci or not
3 java program to find distinct word list from a file
4 Java program to find duplicate character from a string
5 Java Program to find middle index of array where both ends sum is equal
6 Java Program to find line with max character length in descending order in Java
7 Java Program to find max two numbers in an array
8 Java program to find sum of prime numbers
9 Java program to reverse a given number
10 Java program to find permutations of a given string
11 Java program to reverse a given string
12 Java program to find factorial of a given number
13 Java Program for Binary Search
14 Java Program to Add Two 2D Matrix
15 3 Ways to Check if Given Words are Anagram or not
16 Java Program to Find LCM of a Two Given Number
17 Check Given String is Rotation of Another String
18 Java Program To Check If A Given Number is A Perfect Number
19 Remove Common Characters From Given Strings
20 Find Second Largest Number in Array
21 Java Program To Find the Longest Palindrome Present in a String
22 Java Program to Reverse an Array in Place Without Using Any Second Array
23 Java Program to Print 1 To 10 Without Using Loop
24 Write a Java Program to Compare Files in Java
25 Java Program to Find missing Number in an Array
26 Java Program to Find First non Repeated Character in a String
27 Write a Java Program to Find Union and Intersection of Arrays in Java
28 Writing a Java program to rotate an array by d elements.
29 Write a Java program to rotate a matrix
30 Write a Java program to find the largest sum of the contiguous subarray in a given Array

If You Appreciate This, You Can Consider:

  • Share this article on social media or with your teammates.

Suggest Explanation

The suggestion has been saved for review.Thanks for your effort.

{{errorMessage}}

Vertex

Devglan is one stop platform for all
programming tutorials and courses.

About Us

  • About Us
  • Contact Us
  • Submission Criteria
  • Privacy Policy

Quick Links

  • Home
  • Login / Join
  • Submit Your Story
  • Donate

Contact Us

Dhiraj
dhiraj@devglan.com

© 2021 Devglan. All rights reserved.