反向排序HashMap?

时间:2017-03-01 14:59:29

标签: java sorting generics hashmap comparator

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

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

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

1 个答案:

答案 0 :(得分:5)

应在reversed()返回的Comparator上调用comparingByValue()方法。遗憾的是,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
            ));
}