【发布时间】:2014-09-27 05:41:42
【问题描述】:
我有一个 Map 有一个 String 作为 Key 和一个 ArrayList 作为 Value。 ArrayList 基本上是一个以某种方式链接到 key 的四个值的列表。
我的样本数据是:
String : [ArrayList<String>]
"USA": ["25", "5", "20", "4"]
"India": ["15", "7", "8", "2"]
"Canada": ["29", "17", "8", "6"]
我需要按照 ArrayList 中的第一个值对这个 Map 进行降序排序,如下所示:
"Canada": ["29", "17", "8", "6"]
"USA": ["25", "5", "20","4"]
"India": ["15", "7", "8", "2"]
我正在尝试下面的函数,但它不适用于 ArrayList 类型的 Map 值:
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;
}
}
如何修改这个函数来实现我需要的功能?
【问题讨论】:
-
“它不工作”不是问题描述。
标签: java collections arraylist map