Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort map in descending order java8 [duplicate]

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.

like image 812
user3529850 Avatar asked Sep 05 '25 03:09

user3529850


1 Answers

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()));
like image 118
rgettman Avatar answered Sep 07 '25 20:09

rgettman