問題
Map<Key,Value>如何基於Value值排序
精華回答
方法1:
使用TreeMap,可以參考下面的代碼
public class Testing {
public static void main(String[] args) {
HashMap<String,Double> map = new HashMap<String,Double>();
ValueComparator bvc = new ValueComparator(map);
TreeMap<String,Double> sorted_map = new TreeMap<String,Double>(bvc);
map.put("A",99.5);
map.put("B",67.4);
map.put("C",67.4);
map.put("D",67.3);
System.out.println("unsorted map: "+map);
sorted_map.putAll(map);
System.out.println("results: "+sorted_map);
}
}
class ValueComparator implements Comparator<String> {
Map<String, Double> base;
public ValueComparator(Map<String, Double> base) {
this.base = base;
}
// Note: this comparator imposes orderings that are inconsistent with equals.
public int compare(String a, String b) {
if (base.get(a) >= base.get(b)) {
return -1;
} else {
return 1;
} // returning 0 would merge keys
}
}
譯註:如果不自己寫Comparator,treemap默認是用key來排序
方法2:
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;
}
}
譯註:這兩種方法,我簡單測試了下,如果map的size在十萬級別以上,兩者的耗時都是幾百毫秒,第二個方法會快一些。否則,第一個方法快一些。因此,如果你處理的map,都是幾十萬級別以下的大小,兩種方式隨意使用,看個人喜歡了。
stackoverflow鏈接:
http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java
專欄介紹:
非常喜歡stackoverflow,總能在上面找到疑難雜症的解決辦法。偶然發現該網站有一個熱度榜單。於是精選了熱度較高的一些問題,然後按照自己的理解,把大家的討論梳理出來。因此,這些文章不是真正的翻譯,而是按照自己的理解做了一些增刪、潤色,希望能把上面的討論,更精簡有效地分享給大家。
如需轉載,請註明原文地址