【问题标题】:How to sort Map with List by value?如何按值对带有列表的地图进行排序?
【发布时间】:2017-08-12 19:54:44
【问题描述】:

如何按值对带有列表的地图进行排序?我在列表中始终只有一个元素,但我必须使用列表。 我有:

 Map<String,List<String>> map = new HashMap<>();

import java.util.*;

public class MapUtil
{
    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 (o1.getValue()).compareTo( o2.getValue() );
            }
        } );

        Map<K, V> result = new LinkedHashMap<K, V>();
        for (Map.Entry<K, V> entry : list)
        {
            result.put( entry.getKey(), entry.getValue() );
        }
        return result;
    }
}

当我尝试这个时:

MapUtil.sortByValue(map);

我收到此错误:

The method sortByValue(Map<K,V>) in the type MapUtil is not applicable for the arguments (Map<String,List<String>>)

【问题讨论】:

    标签: java


    【解决方案1】:

    V 需要实现可比较,但 List&lt;String&gt; 不需要。您需要更改排序方法以使用显式comparator

    【讨论】:

    • 你能写出在哪里以及如何使用显式比较器,因为这个例子是我从堆栈示例中得到的
    • this
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多