sort HashMap in reverse? [duplicate]

左心房为你撑大大i 提交于 2020-02-24 12:09:07

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/42535050/sort-hashmap-in-reverse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!