Monday, 11 December 2017

Java Program to Count Occurrence of Word in a Sentence

     In this post, we can learn how to count the word occurrences in a given String. In this code, first split the String sentence using space as delimiter . Use any map to store the word as a key and number occurrence as value in the Integer form.

See the below code,

package com.test;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class WordsOccurances {

     public static void main(String[] args) {
  
          String sentence = "Java can run on many different operating "
              + "systems. This makes Java platform independent.";
  
          String[] words = sentence.split(" ");
          Map<String, Integer> wordsMap = new HashMap<String, Integer>();
  
          for (int i = 0; i<words.length; i++ ) {
              if (wordsMap.containsKey(words[i])) {
                   Integer value = wordsMap.get(words[i]);
                   wordsMap.put(words[i], value + 1);
              } else {
                   wordsMap.put(words[i], 1);
              }
          }
  
            /*Now iterate the HashMap to display the word with number 
             of time occurance    */
  
          Iterator it = wordsMap.entrySet().iterator();
          while (it.hasNext()) {
               Map.Entry<String, Integer> entryKeyValue = (Map.Entry<String, Integer>) it.next();
               System.out.println("Word : "+entryKeyValue.getKey()+", Occurance : "
                    +entryKeyValue.getValue()+" times");
          }
     }
} 
 
 
Output :-- 
Word : Java, Occurance : 2 times
Word : can, Occurance : 1 times
Word : systems., Occurance : 1 times
Word : independent., Occurance : 1 times
Word : makes, Occurance : 1 times
Word : This, Occurance : 1 times
Word : run, Occurance : 1 times
Word : operating, Occurance : 1 times
Word : many, Occurance : 1 times
Word : different, Occurance : 1 times
Word : platform, Occurance : 1 times
Word : on, Occurance : 1 times 

Related Post :--
1) String Related Interview Questions  
2) How HashMap works internally in Java?  
3) How to iterate the TreeMap in reverse order in Java  
4) Collection Interview Questions and Answers in Java(List,Map & Set)
5) Exception Handling Interview questions and answers
6) Spring @Qualifier Annotation with example

No comments:

Post a comment