按Java8降序对地图进行排序 [英] Sort map in descending order java8

查看:114
本文介绍了按Java8降序对地图进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 ?

我可以这样:

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.

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.

推荐答案

您可以使用

You can use Comparator's default method reversed() to reverse the sense of comparisons to sort it descending.

这里的类型推断似乎有点不足,但是向comparingByValue()提供显式的类型参数可以解决此问题.

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()));

这篇关于按Java8降序对地图进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆