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;
}
这是来自这篇文章的一个示例。它可以正常工作,但问题在于它按升序排序。我该如何将其更改为降序?
我可以像这样做:
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表达式。
.forEach/.forEachOrdered
向映射中添加条目,而是使用Collectors.toMap
进行收集。 - Alexis C.