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 

import java.util.*;

import java.util.regex.*;

import java.io.*;



public class Frequency {

public static void main(String[] args) {

String str;

Scanner in = new Scanner(System.in);

System.out.println("Enter line of String: ");

str = in.nextLine();

System.out.println("Using the First Method");

findOccurrence(str);

System.out.println("Using the Second Method");

findOccurrence1(str);

}

//Finding number of occurrence of a word in a string using Regex , ArrayList & HashSet

private static void findOccurrence( String inputStr)

{

List wordList = Arrays.asList(inputStr.split("\s+")); //for spliting by white space

HashSet hashSet = new HashSet(wordList); // Remove duplicates

wordList = new ArrayList(hashSet) ;



for (String word:wordList)

{

int count=0;

Pattern p = Pattern.compile(word );

Matcher matcher = p.matcher(inputStr);

boolean found = matcher.find();

while(found) {

found = matcher.find();

count++;

}

System.out.println(word + " " + count);

}
}



//Finding number of occurrence of a word in a string using Map

public static void findOccurrence1(String inputStr)

{



List wordList = Arrays.asList(inputStr.split("\s+"));

Map map = new TreeMap();

for (String word :wordList) {

Integer count = map.get(word);

map.put(word, (count == null ? 1 : count + 1));

}

System.out.println(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}

Leave a Reply