packagecom.thealgorithms.others;importjava.io.*;importjava.util.*;publicclassTopKWords{staticclassCountWords{privateString fileName;publicCountWords(String fileName){this.fileName = fileName;}publicMap<String,Integer>getDictionary(){Map<String,Integer> dictionary =newHashMap<>();FileInputStream fis =null;try{
fis =newFileInputStream(fileName);// open the fileint in =0;String s ="";// init a empty word
in = fis.read();// read one characterwhile(-1!= in){if(Character.isLetter((char) in)){
s +=(char) in;// if get a letter, append to s}else{// this branch means an entire word has just been readif(s.length()>0){// see whether word exists or notif(dictionary.containsKey(s)){// if exist, count++
dictionary.put(s, dictionary.get(s)+1);}else{// if not exist, initiate count of this word with 1
dictionary.put(s,1);}}
s ="";// reInit a empty word}
in = fis.read();}return dictionary;}catch(IOException e){
e.printStackTrace();}finally{try{// you always have to close the I/O streamsif(fis !=null){
fis.close();}}catch(IOException e){
e.printStackTrace();}}returnnull;}}publicstaticvoidmain(String[] args){// you can replace the filePath with yoursCountWords cw =newCountWords("/Users/lisanaaa/Desktop/words.txt");Map<String,Integer> dictionary
= cw.getDictionary();// get the words dictionary: {word: frequency}// we change the map to list for convenient sortList<Map.Entry<String,Integer>> list =newArrayList<>(dictionary.entrySet());// sort by lambda valueComparator
list.sort(Comparator.comparing(m -> m.getValue()));Scanner input =newScanner(System.in);int k = input.nextInt();while(k > list.size()){System.out.println("Retype a number, your number is too large");
input =newScanner(System.in);
k = input.nextInt();}for(int i =0; i < k; i++){System.out.println(list.get(list.size()- i -1));}
input.close();}}