0
letterFrequencies.entrySet().stream()
        .sorted(Map.Entry.comparingByValue().reversed())
        .collect(Collectors.toMap(Entry::getKey, Entry::getValue));

I'm currently using this to try but I get an error which says 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>>>>)

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
KONADO
  • 189
  • 1
  • 13
  • 4
    `Collectors.toMap` - oops. Even if you get your `Comparator` to work, dumping the result into a `HashMap` isn't going to yield anything useful. – Boris the Spider Nov 26 '17 at 14:07

2 Answers2

4

try something like:

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

Also, as mentioned by Boris the Spider, dumping the result into a HashMap will not maintain insertion order hence the use of LinkedHashMap here.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
0

You can pass the Comparator.reverseOrder() like this and collect into LinkedHashMap

letterFrequencies.entrySet().stream()
            .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                    (v1, v2) -> v1, LinkedHashMap::new));