Java count frequency of words in the string


 

Java count frequency of words in the string

In this tutorial, you will learn how to count the occurrence of each word in the given string.

In this tutorial, you will learn how to count the occurrence of each word in the given string.

Java count frequency of words in the string.

In this tutorial, you will learn how to count the occurrence of each word in the given string.

String manipulation forms the basis of many algorithms and utilities such as text analysis, input validation, and file conversion. Here we are going to find the frequency of words in a string. In the given example, we have accepted a sentence as a string from the user and convert it to String[] where each element of the array represents a single word. Then we have used a Map to map Map<String,Integer> the words with frequency.

Example:

import java.util.*;

public class CountWordOccurrence {
public static void main(String[] args){
Scanner input=new Scanner(System.in);
System.out.print("Enter string: ");
String string=input.nextLine();
String[] st = string.split(" ");
HashMap<String, Integer> map = new HashMap<String, Integer>();
String str="";
for(int i=0;i<st.length;i++){
str+=st[i]+" ";
}
str = str.toLowerCase(); 
int count = -1;
for (int i = 0; i < str.length(); i++) { 
if ((!Character.isLetter(str.charAt(i))) || (i + 1 == str.length())) { 
if (i - count > 1) { 
if (Character.isLetter(str.charAt(i))) 
i++;
String word = str.substring(count + 1, i);
if (map.containsKey(word)) { 
map.put(word, map.get(word) + 1);
}
else { 
map.put(word, 1);
} 
} 
count = i;
} 
} 
ArrayList<Integer> list = new ArrayList<Integer>();
list.addAll(map.values());
Collections.sort(list, Collections.reverseOrder());
int last = -1;
for (Integer i : list) { 
if (last == i) 
continue;
last = i;
for (String s : map.keySet()) { 
if (map.get(s) == i) 
System.out.println(s + ":" + i);
} 
} 
} 
}

Output:

Enter string: where there is will there is a way
is:2
there:2
a:1
will:1
way:1
where:1

Ads