letterFrequencies.entrySet().stream()
.sorted(Map.Entry.comparingByValue().reversed())
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
我目前正在尝试使用此功能,但收到错误消息The method sorted(Comparator<? super Map.Entry<Character,Integer>>) in the type Stream<Map.Entry<Character,Integer>> is not applicable for the arguments (Comparator<Map.Entry<Object,Comparable<? super Comparable<? super V>>>>)
答案 0 :(得分:4)
尝试类似:
LinkedHashMap<Character, Integer> resultSet =
letterFrequencies.entrySet().stream()
.sorted(Map.Entry.<Character, Integer>comparingByValue().reversed())
.collect(Collectors.toMap(Entry::getKey, Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
另外,正如Boris the Spider所提到的,将结果转储到HashMap
将不会维持插入顺序,因此在此处使用LinkedHashMap
。