反向排序HashMap?

sort HashMap in reverse?

所以我遇到了这个能够按值对 HashMap 进行排序的方法。

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

我想在 Comparator 上使用 reversed() 方法,但我似乎找不到合适的位置。

应该在 comparingByValue() 返回的 Comparator 上调用 reversed() 方法。不幸的是,Java 的类型推断在这里失败了,因此您必须指定通用类型:

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