In this tutorial, I am going to show you the most important question in Java Interview. How to find duplicate words count in a file.

Input : Give a Text file with duplicate words like below :

Java 8 Tutorials
Java 8 Examples
Online Tutorials Point
Java 7 Examples
Java 7 try with resources example

Output :

examples -> 2
java8 -> 2
tutorials -> 2
java7 -> 2
with -> 1
online -> 1
resources -> 1
try -> 1
point -> 1
example -> 1

 

Find Duplicate Words Count in a File :

[java]

package com.onlinetutorialspoint.javaprograms;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

public class DuplicateWordsCount {
    public Map<String, Integer> getMapWithCount(String fileName) {

        Map<String, Integer> map = new HashMap<String, Integer>();
        try (FileInputStream fis = new FileInputStream(fileName);
                DataInputStream dis = new DataInputStream(fis);
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        dis))) {

            String line = null;
            while ((line = br.readLine()) != null) {
                StringTokenizer st = new StringTokenizer(line, " ");
                while (st.hasMoreTokens()) {
                    String tmp = st.nextToken().toLowerCase();
                    if (map.containsKey(tmp)) {
                        map.put(tmp, map.get(tmp) + 1);
                    } else {
                        map.put(tmp, 1);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }

    public static void main(String a[]) {
        DuplicateWordsCount mdc = new DuplicateWordsCount();
        Map<String, Integer> wordMap = mdc
                .getMapWithCount("/home/chandrashekhar/Desktop/sample.txt");
        
        wordMap.entrySet().stream().sorted(Map.Entry.<String, Integer>comparingByValue().reversed()
                ).forEachOrdered((entry)->System.out.println(entry.getKey() +" -> "+entry.getValue()));
    }
}
[/java]

Recommended : try with resources in Java 7

Recommended : How to sort a map in Java 8

examples -> 2
java8 -> 2
tutorials -> 2
java7 -> 2
with -> 1
online -> 1
resources -> 1
try -> 1
point -> 1
example -> 1

Happy Learning 🙂