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 中的示例邮政。有用。问题是它按升序排序。如何将其更改为降序?
我可以这样做:
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;
}
我可以通过更改此行的顺序来做到这一点:return (o2.getValue()).compareTo( o1.getValue() );
但我想尝试使用 lambda expr。
最佳答案
您可以使用Comparator
's default method reversed()
反转比较的意义以降序排序。
这里的类型推断似乎有点偏离,但向 compareByValue()
提供显式类型参数可以解决该问题。
st.sorted( Map.Entry.<K, V>comparingByValue().reversed() )
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
关于java - java8 按降序对映射进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36754724/