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());
Written by Bruno Candido Volpato da Cunha
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Java
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#