HashMap如何进行反向排序?

3

我发现了一种能够按值对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()方法,但我似乎找不到正确的位置放置它。


https://dev59.com/JV4b5IYBdhLWcg3w3k6Y#28607267 - Jason C
@JornVernee 那个不起作用。 - Ben Arnao
"不工作"? "不工作" 是指什么? - Lew Bloch
@LewBloch .sorted(Map.Entry.comparingByValue().reversed()) 无法编译。Mureinik的解决方案可行。 - Ben Arnao
1个回答

11

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

3
这正是为什么在问题中包含你尝试过的内容以及清晰地描述为什么你所尝试的方法无效通常是一个好主意的原因。 - Jason C
2
谢谢,这正是我需要的。我尝试在那个地方使用reversed(),但它没有起作用,因为我必须指定类型。 - Ben Arnao

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接