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>>>>)
最佳答案
尝试这样的事情:
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
。
关于java - 尝试按值对链接的 HashMap <Character, Integer> 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47496993/