Wednesday, 23 September 2015

How to count occurrence of word in String Array


The most basic technical question asked in interview to find the count of occurrence of words in String array.we can also find count of occurrence of characters in String by simple converting String into array.

In this solution we have used Hashtable where we keep word as a key and count of its occurrence as value.

import java.util.Hashtable;  
 /**  
  *   
  */  
 /**  
  * @author Dixit  
  *   
  */  
 public class CountOfWordOccurence {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           String []s={"bat","ball","bat"};  
           Hashtable<String, Integer> hashtable=setup(s);  
           System.out.println("Occurrences of bat is:"+getFrequency(hashtable, "bat"));  
           System.out.println("Occurrences of ball is:"+getFrequency(hashtable, "ball"));  
      }  
      static Hashtable<String, Integer> setup(String[] array) {  
           Hashtable<String, Integer> table = new Hashtable<String, Integer>();  
           for (String word : array) {  
                word = word.toLowerCase();  
                if (word.trim() != "") {  
                     if (!table.containsKey(word))  
                          table.put(word, 0);  
                     table.put(word, table.get(word) + 1);  
                }  
           }  
           return table;  
      }  
      static int getFrequency(Hashtable<String, Integer> table, String word) {  
           if (table == null || word == null)  
                return -1;  
           word = word.toLowerCase();  
           if (table.containsKey(word)) {  
                return table.get(word);  
           }  
           return 0;  
      }  
 }  


Output  
 Occurrences of bat is:2  
 Occurrences of ball is:1  

Enjoy Programming.

No comments:

Post a Comment