Articles

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

Share

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:

 

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

This post was last modified on December 27, 2020

Sandeep Verma

Published by
Sandeep Verma
Tags: duplicate string java java program java program to count number of repeated words in a string using hashmap java program to count number of repeated words in a string without using hashmap Program to find the duplicate words in a string String duplicate words