Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort HashMap in reverse? [duplicate]

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.

like image 240
Ben Arnao Avatar asked Jun 02 '26 22:06

Ben Arnao


1 Answers

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
            ));
}
like image 95
Mureinik Avatar answered Jun 04 '26 12:06

Mureinik