问题
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