4
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.

Community
  • 1
  • 1
user3529850
  • 1,632
  • 5
  • 32
  • 51
  • 1
    before we answer that, [what have you tried, yourself](/help/how-to-ask)? where have you looked to find the answer, what have you tinkered with, have you looked up the documentation for the API calls you see in this code, etc? – Mike 'Pomax' Kamermans Apr 20 '16 at 20:40
  • 1
    By the way, do not use `.forEach/.forEachOrdered` for adding entries to the map, just use collect with `Collectors.toMap` instead. – Alexis C. Apr 20 '16 at 21:43

2 Answers2

15

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()));
rgettman
  • 176,041
  • 30
  • 275
  • 357
0

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)}
HopefullyHelpful
  • 1,652
  • 3
  • 21
  • 37