尝试按值对链接的HashMap <character,integer =“”>进行排序

时间:2017-11-26 14:06:23

标签: java sorting linkedhashmap

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>>>>)

1 个答案:

答案 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