3

So I came across this method which is able to sort HashMaps by value.

public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
        return map.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue())
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (e1, e2) -> e1,
                        LinkedHashMap::new
                        ));
    }

I want to use the reversed() method on the Comparator but I can't seem to find the right place to put it.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Ben Arnao
  • 153
  • 4
  • 14

1 Answers1

11

The reversed() method should be called on the Comparator returned by comparingByValue(). Java's type inference breaks down here, unfortunately, so you'll have to specify the generic types:

public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue
    (Map<K, V> map) {

    return map.entrySet()
            .stream()
            .sorted(Map.Entry.<K, V> comparingByValue().reversed())
            // Type here -----^ reversed() here -------^
            .collect(Collectors.toMap(
                    Map.Entry::getKey,
                    Map.Entry::getValue,
                    (e1, e2) -> e1,
                    LinkedHashMap::new
            ));
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 3
    @BenArnao Which is exactly why it's generally a good idea to include what you've tried in your question as well as clear descriptions of why what you tried hasn't worked. – Jason C Mar 01 '17 at 15:07
  • 2
    Thanks, this is what i needed. I tried using reversed() at that place but it didn't work because i had to specify the type. – Ben Arnao Mar 01 '17 at 15:07