1
如何按值列表按地圖排序?我在列表中總是有一個元素,但我必須使用列表。 我:如何按值列表對Map進行排序?
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>>)
你可以寫在哪裏和如何使用顯式比較器,因爲這個例子我從棧示例 – JavaCoder
看到[this](https://stackoverflow.com/questions/35761864/java-sort-list-of-lists#answer -35761935)。 – saka1029