package Others;
import java.io.*;
import java.util.*;
public class TopKWords {
static class CountWords {
private String fileName;
public CountWords(String fileName) {
this.fileName = fileName;
}
public Map<String, Integer> getDictionary() {
Map<String, Integer> dictionary = new HashMap<>();
FileInputStream fis = null;
try {
fis = new FileInputStream(fileName);
int in = 0;
String s = "";
in = fis.read();
while (-1 != in) {
if (Character.isLetter((char) in)) {
s += (char) in;
} else {
if (s.length() > 0) {
if (dictionary.containsKey(s)) {
dictionary.put(s, dictionary.get(s) + 1);
} else {
dictionary.put(s, 1);
}
}
s = "";
}
in = fis.read();
}
return dictionary;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
public static void main(String[] args) {
CountWords cw = new CountWords("/Users/lisanaaa/Desktop/words.txt");
Map<String, Integer> dictionary =
cw.getDictionary();
List<Map.Entry<String, Integer>> list = new ArrayList<>(dictionary.entrySet());
list.sort(Comparator.comparing(m -> m.getValue()));
Scanner input = new Scanner(System.in);
int k = input.nextInt();
while (k > list.size()) {
System.out.println("Retype a number, your number is too large");
input = new Scanner(System.in);
k = input.nextInt();
}
for (int i = 0; i < k; i++) {
System.out.println(list.get(list.size() - i - 1));
}
input.close();
}
}