简体   繁体   English

如何按值对带有列表的地图排序?

[英]How to sort Map with List by value?

How can I sort Map with list by value?I have in list always one element but i must use list. 我如何按值对列表进行排序?我在列表中总是有一个元素,但我必须使用列表。 I have: 我有:

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

And

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;
    }
}

and when i try this: 当我尝试这个:

MapUtil.sortByValue(map);

I get this error: 我收到此错误:

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

V needs to implement comparable, but List<String> does not. V需要实现可比的,但是List<String>不需要。 You need to change the sorting method to use explicit comparator . 您需要更改排序方法以使用显式比较器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM