Java Program to Find a Frequency of Words

In this tutorial, we will see how to calculate the frequency of words present in a String in java.

Frequency refers to the number of times that have occurred. In this program, we will count how many time each word are repeated and display the result for each word’s frequency.

The program splits each word with space count present after every word, split() and equals() functions are used in the following java program.


Java Program to Find a Frequency of Words

//find a frequency of words

 public class RepeatedWord
 {
 
  public static void main(String[] args)
  {
      String input="Welcome to java java Simle2code to java";  //String
      
      String[] words = input.split(" ");  //Split the word from String
      int wc = 1;    //word count initiated
      
      for(int i=0; i < words.length;i++)  
      {
        for(int j = i+1; j < words.length;j++) 
        {
         if(words[i].equals(words[j]))  //Checking for both strings are equal
         {
           wc = wc+1;    //if equal increment the count
           words[j]="0"; //Replace repeated words by zero
         }
        }
        if(words[i]!="0")
        System.out.println(words[i]+"--"+wc); //Display
        wc=1;
        
      }  
  }
}

Output:

Welcome--1
to--2
java--3
Simle2code--1