按降序排序映射java8 [重复]

2024-05-14

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 expr。


您可以使用Comparator的默认方法reversed() https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#reversed--反转比较的意义以降序排序。

类型推断似乎有点偏离这里,但提供显式类型参数comparingByValue()解决了这个问题。

st.sorted( Map.Entry.<K, V>comparingByValue().reversed() )
       .forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

按降序排序映射java8 [重复] 的相关文章

随机推荐