Find the word with maximum occurrences in a line
Question : Count the number of occurrences of each word in a String
Write a program to accept a string from the user and print the number of times each word of the string occurs in the input string.
If the input is "Tinkle Twinkle little star" then the output should be
Twinkle  - 2
little        -1
star         -1
import java.util.HashMap;
import java.util.Scanner;

class CountOccurances{
   public static void main(String args[]){
      CountOccurances obj = new CountOccurances();
      System.out.println("Enter the line of String");
      String max = obj.maxOccurances(new Scanner(" "));
      System.out.println("Word with maximum occurances = " + max);

   public String maxOccurances(String[] str){
      HashMap<String,Integer> map = new HashMap<String,Integer>();
      for(int itr=0;itr<str.length;itr++){
           map.put(str[itr], map.get(str[itr]) +1);
      String word = null; 
      int max = 0;
      for(String token : map.keySet()){
         System.out.println("word = " + token + "   occurrences = " + map.get(token) );
         if(map.get(token) > max){
           max  = map.get(token);
           word = token;
      return word;
Enter the line of String
this is a random text from a text book with unknown text                                                 
word = with    occurrences = 1
word = text    occurrences = 3
word = is      occurrences = 1
word = a       occurrences = 2
word = book    occurrences = 1
word = random  occurrences = 1
word = unknown occurrences = 1
word = from    occurrences = 1
word = this    occurrences = 1
Word = with maximum occurances = text
Logic : Concept to be used
We will make use of HashMap and use String as the key and Integer as value to store the number of times each word occurs in a given line. Now we need to add each word of the line to the HashMap and count the number of occurrences of each word.

We will traverse the line of string and add each word to HashMap. Before adding the word to the HashMap we will check if the word already exists in the map
  • if it exists -  then we will increment the occurrence of the word by increasing its value by 1.
  • if does not exist - then we will add the word to the map and add its value as 1.
Now, we will traverse through the map and find the word with the maximum number of occurrences.

No comments :

Post a Comment