Java Program to count Occurrence ( Frequency) of each word in a line

The program given below is to find the number of times a word occurs in a String . Let us see  in two ways .
    1. Using Regex , ArrayList and  HashSet. 
   2. Using Map.
              In the below program,  in the first method , we are using HashSet to remove the duplicates . Now the array list has values without any duplicates. Taking the first word from the list , we are searching the word in the original string using Regex , if the word is found in the string , then count is incremented , this search continues until the end of the string. Then take the next word from the list and search continues…
         
             In Second method , the program declares a map from String to Integer, for storing the word and the number of occurrence of the word . The arraylist has all the words of the input string. Iteration starts over each word on the array list . For each word in the array list, it looks up the word in the map using Integer count = map.get(word);. if count is null, this is the first occurrence of the word, so it puts 1 into the map. Otherwise, it adds 1 to existing count and puts the value into the map 

Enter line of String:
Mumbai Delhi NewYork Chennai NewYork Canada Delhi Bangalore Chennai NewYork Chennai

Using the First Method
Mumbai 1
NewYork 3
Bangalore 1
Canada 1
Chennai 3
Delhi 2

Using the Second Method
{Bangalore=1, Canada=1, Chennai=3, Delhi=2, Mumbai=1, NewYork=3}

You may also like

Leave a Reply