Sort map in descending order java8 [duplicate]

安稳与你 提交于 2020-02-22 08:29:17

问题


private static <K, V extends Comparable<? super V>> Map<K, V>
    sortByValue( Map<K, V> map )
    {
        Map<K, V> result = new LinkedHashMap<>();
        Stream<Map.Entry<K, V>> st = map.entrySet().stream();

        st.sorted( Map.Entry.comparingByValue() )
                .forEachOrdered( e -> result.put(e.getKey(), e.getValue()) );

        return result;
    }

This is an example from this post. It works. the problem is that it sorts in ascending order. How can I change it to descending ?

I can do that like this:

public static <K, V extends Comparable<? super V>> Map<K, V>
sortByValue( Map<K, V> map )
{
    List<Map.Entry<K, V>> list =
            new LinkedList<Map.Entry<K, V>>( map.entrySet() );
    Collections.sort( list, new Comparator<Map.Entry<K, V>>()
    {
        public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 )
        {
            return (o2.getValue()).compareTo( o1.getValue() );//change o1 with o2
        }
    } );

    Map<K, V> result = new LinkedHashMap<K, V>();
    for (Map.Entry<K, V> entry : list)
    {
        result.put( entry.getKey(), entry.getValue() );
    }
    return result;
}

I can do that by changing order i this line: return (o2.getValue()).compareTo( o1.getValue() ); But I would like to try with lambda expr.


回答1:


You can use Comparator's default method reversed() to reverse the sense of comparisons to sort it descending.

The type inference seems to be a little off here, but supplying explicit type arguments to comparingByValue() fixes the issue.

st.sorted( Map.Entry.<K, V>comparingByValue().reversed() )
       .forEachOrdered(e -> result.put(e.getKey(), e.getValue()));



回答2:


you can use the already provided comparator and multiply the compareTo return-value by -1 or simply swap the arguments (to account for the corner cases).

(a,b)-->{comparingByValue().compareTo(b,a)}


来源:https://stackoverflow.com/questions/36754724/sort-map-in-descending-order-java8

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