[英]How to sort a Map by Key and Value, whereas the Val is a Map/List itself
[英]How to sort Map with List by value?
我如何按值对列表进行排序?我在列表中总是有一个元素,但我必须使用列表。 我有:
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>>)
V
需要实现可比的,但是List<String>
不需要。 您需要更改排序方法以使用显式比较器 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.