I have a Map<String, Integer>
mapping "words" to their number of occurrences in a larger original String
.
I'm making a word cloud and I need to render the words with the greatest number of occurrences first to make sure they don't get truncated when there isn't enough room to render them after too many smaller words have been placed.
I tried doing something like:
public static WordCounter getSortedWordCounter(WordCounter wordCounter) {
Map<String, Integer> sortedWordCountMap = wordCounter.getAll().entrySet().stream()
.sorted(Entry.comparingByValue(Comparator.reverseOrder()))
.limit(10)
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
return new WordCounter(sortedWordCountMap);
}
This gives me a WordCounter
with the top 10 results but since Collectors.toMap
is returning a regular Map
, their order isn't sorted, it's random.
If I try storing the result of the stream()
into a LinkedHashMap<String, Integer>
it tells me I can't use Entry::getKey
or Entry::getValue
in a static context because Collectors.toMap()
is static.