use*_*850 2 java sorting dictionary java-8
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;
}
Run Code Online (Sandbox Code Playgroud)
这是这篇文章的一个例子.有用.问题是它按升序排序.如何将其更改为降序?
我可以这样做:
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;
}
Run Code Online (Sandbox Code Playgroud)
我可以通过改变这一行的顺序来做到这一点:return (o2.getValue()).compareTo( o1.getValue() );但我想尝试使用lambda expr.
您可以使用Comparator默认方法reversed()来反转比较感,以便对其进行降序排序.
类型推断似乎有点偏离这里,但提供显式类型参数来comparingByValue()修复问题.
st.sorted( Map.Entry.<K, V>comparingByValue().reversed() )
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
Run Code Online (Sandbox Code Playgroud)