
hi i want to Map words to line number in text file and show occurrence of word in java coding

Here is a code that reads the text file and count the occurrence of each word from the file and display it on the console.
import java.io.*;
import java.util.*;
public class CountWordOccurrence {
public static void main(String[] args){
try{
BufferedReader br=new BufferedReader(new FileReader("c:/data.txt"));
String str="";
String st;
while((st=br.readLine())!=null){
str+=st+" ";
}
HashMap<String, Integer> map = new HashMap<String, Integer>();
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);
}
}
}
catch(Exception e){
System.out.println(e);
}
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.