Java Program to Find Duplicate Words And Their Occurrences in String With or Without Using Map

The program prints repeated words with number of occurrences in a given string using Map or without Map. It first creates an array from given string using split method and then after considers as any word duplicate if a word come atleast two times. For example, “blue sky and blue ocean” in this blue is repeating word with 2 times occurrence.

In this article, there are two ways used to achieve the solution, using Map and using String Array.

1. Java Program to find occurrences of the duplicate words in a sequence of string without using Map

Program:

class DuplicateWordsWithoutUsingMap {
    public static void main(String[] args) {
        String str = " this is is the word this is this";
        int count;
        String duplicates = "";
        String[] words = str.toLowerCase().trim().split(" ");
        for (int i = 0; i < words.length; i++) {
            count = 1;
            for (int j = i + 1; j < words.length; j++) {
                if (words[i].equals(words[j])) {
                    count++;
                }
            }
            if (count > 1) {
                if (duplicates.isEmpty()) {
                    duplicates += " " + words[i] + " : " + count;
                } else if (!duplicates.matches("(.*) " + words[i] + " (.*)")) {
                    duplicates += " " + words[i] + " : " + count;
                }
            }
        }
        System.out.println(duplicates);
    }
}

Output:

blo

 

2. Java Program to find occurrences of the duplicate words in a sequence string with the help of Map

Program:

class DuplicateWords {
    public static void main(String[] args) {
        String str = "This is a program to find duplicate words in a string, again! a program";
        String[] words = str.toLowerCase().trim().split(" ");
        Map<String, Integer> duplicateString = new HashMap<>();
        int count = 1;
        for (String x : words) {
            if (duplicateString.containsKey(x)) {
                duplicateString.put(x, duplicateString.get(x) + 1);
            } else {
                duplicateString.put(x, count);
            }
        }
        System.out.println("Duplicate Words in a String : ");
        for (Map.Entry a : duplicateString.entrySet()) {
            int val = (Integer) a.getValue();
            if (val > 1) {
                System.out.println(a);
            }
        }
    }
}

Output:

Duplicate Words in a String : 
a=3
program=2

Leave a Reply