I'd like to sort an existing TreeMap (or copy the values from a Map into a TreeMap, doesn't matter) in an descending order, sorted by value (Doubles).
I know there are a lot of similar questions posted here, but afaik in Java8 you can accomplish this without creating an own Comparator, but using Collections.reverseOrder.
Somewhere there was an answer which described exactly this. Based on it, I tried to implement it:
private Map<String, Double> orderByDescValue(Map<String, Double> unorderedMap) {
Stream<Map.Entry<String,Double>> sorted = unorderedMap.entrySet().stream()
.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()));
return sorted.limit(Configuration.WORDCLOUD_SIZE)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
I understand this doesn't work because it returns a Map, which doesn't assert any order, instead of a TreeMap. But Collectors doesn't seem to have a toTreeMap, I can't cast it - and I do not know what else to do.
Or maybe it can't work this way and I have to solve this another way?