Find All Repeated Words In Text File And Their Occurrences In Java
Place your file location in the argument of the FileReader.
If the input text file contain :
Details
Name = Amit
Address = Bangalore
Name = Anuj
Address = Bangalore
The output will be look like
The string --> Details <-- repeated 1
The string --> Address <-- repeated 2
The string --> Amit <-- repeated 1
The string --> = <-- repeated 4
The string --> Anuj <-- repeated 1
The string --> Name <-- repeated 2
The string --> Bangalore <-- repeated 2
import java.io.BufferedReader;
import java.util.HashMap;
import java.io.FileReader;
import java.io.IOException;
import java.util.Set;
public class RepeatedWordInFile {
public static void main(String[] args)
{
BufferedReader br=null;
try
{
br = new BufferedReader(new FileReader("G:\\my.txt"));
HashMap<String,Integer> myhashmap = new HashMap<String,Integer>();
String str;
while((str=br.readLine())!=null)
{
String[] splitstring=str.split(" ");
for(String allstr:splitstring)
{
if(!myhashmap.containsKey(allstr))
{
myhashmap.put(allstr,1);
}
else
{
myhashmap.put(allstr,myhashmap.get(allstr)+1);
}
}
}
Set<String> myset=myhashmap.keySet();
for(String strng:myset)
{
System.out.println("The string -->"+" "+strng+" "+"<-- repeated"+" "+myhashmap.get(strng));
}
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try
{
br.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
}
No comments:
Post a Comment