Write a Java program that reads a text file and then create
Write a Java program that reads a text file and then create an output file that contains word counts with line numbers. The output should be sorted by their word counts. And you must use HashMap or TreeMap in your program.
Example,
Input file:
You love NPU
NPU loves you and you all
Output file: (word, count, line numbers)
you 3 1,2
NPU 2 1,2
love 1 1
loves 1 2
and 1 2
all 1 2
Solution
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class wordFrequency {
public static void main(String[] args) {
File file = new File(\"data.txt\");
String[] words = new String[];
int index = 0;
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String word = sc.nextLine();
words[index] = word;
index++;
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
// counting words frequency
Map<String, Integer> map = new HashMap<>();
for (String w : words) {
Integer num = map.get(w);
num = (num == null) ? 1 : ++num;
map.put(w, num);
}
// printing back
for (Map.Entry entry : map.entrySet()){
System.out.println(entry.getKey() + \" \" + entry.getValue());
}
}
}
