Find repeated Words Count in a String

This is a very common question where you have to find duplicate word in a given string. Let’s say you have a string

This is a String with some duplicate words in it. duplicate words are printed with count by this program.

Algorithm:

  • We will first split the words withe “ ” (blank space) as a delimiter as in a sentence each word is separated by a space, which will return an array of String. Iterate over the array, here we will use hashMap to keep the word and its count against that. 
  • The logic goes this way check for word in the map , if found increment the counter else add the word.
  • At last print the all the elements of the map.
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

public class DuplicateWordInString {

 public static void main(String[] args) {
  System.out.print("Enter string == ");
  Scanner scanner = new Scanner(System.in);
  String inputString = scanner.nextLine();
  scanner.close();

  String[] words = inputString.split(" ");

  Map < String, Integer > wordMap = new HashMap < > ();
  for (int i = 0; i < words.length; i++) {
   Integer count = wordMap.get(words[i]);
   if (count == null) {
    wordMap.put(words[i], 1);
   } else {
    count++;
    wordMap.put(words[i], count);
   }
  }

  Set < Map.Entry < String, Integer >> entrySet = wordMap.entrySet();
  for (Map.Entry < String, Integer > entry: entrySet) {
   System.out.println(entry.getKey() + "==" + entry.getValue());
  }
 }
}

Output of the program is :

Enter string == This is a String with some duplicate words in it. duplicate words are printed with 
count by this program.
a==1
some==1
it.==1
in==1
words==2
count==1
this==1
is==1
String==1
duplicate==2
with==2
printed==1
are==1
by==1
This==1
program.==1

 

core java 12

FOLLOW US ON LinkedIn



Explore Tutu'rself