Last Updated: September 12, 2021
·
24
· Bruno Volpato

Sort words by their frequency

Map<String, Integer> freq = new HashMap<>();

for (String word : words) {
    if (!freq.containsKey(word)) {
        freq.put(word, 0);
    }

    freq.put(word, freq.get(word) + 1);
}


List<String> kWords = freq.entrySet()
    .stream()
    .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()));
    .map(Map.Entry::getKey)
    .limit(k)
    .collect(Collectors.toList());