classSolution{publicList<String>topKFrequent(String[] words,int k){Map<String,Integer> map =newHashMap<>();// Count the wordsfor(int i =0; i < words.length;++i){
map.put(words[i], map.getOrDefault(words[i],0)+1);}// ResultList<String> res =newArrayList(map.keySet());// Sort it lexicographically if 2 words have the same freq.Collections.sort(res,(w1, w2)->
map.get(w1).equals(map.get(w2))?
w1.compareTo(w2): map.get(w2)- map.get(w1));return res.subList(0, k);}}
classSolution{publicList<String>topKFrequent(String[] words,int k){Map<String,Integer> map =newHashMap<>();// Store frequenciesfor(String word : words){
map.put(word, map.getOrDefault(word,0)+1);}// ResultList<String> res =newArrayList(map.keySet());// Sort it lexicographically if 2 words have the same freq.Collections.sort(res,(w1, w2)->{int w1Count = map.get(w1);int w2Count = map.get(w2);// If the counts are equal, then use String.compareTo to lexigraphically compare the stringsif(w1Count == w2Count){return w1.compareTo(w2);}else{// Else sort by greatest countreturn w2Count - w1Count;}});return res.subList(0, k);}}