map 按value 排序

public Map sortByValue(Map<Integer,Integer> map){
		Map<Integer,Integer> res=new LinkedHashMap<Integer,Integer>();
		List<Map.Entry<Integer, Integer>> sortList=new ArrayList<Map.Entry<Integer,Integer>>(map.entrySet());
		Collections.sort(sortList,new Comparator<Map.Entry<Integer, Integer>>(){

			@Override
			public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
				// TODO Auto-generated method stub
				return o2.getValue()-o1.getValue();
			}
			
		});
		for(Entry<Integer,Integer> en:sortList){
			res.put(en.getKey(), en.getValue());
		}
		return res;
		
	}

上面這種是肯定好用的

還有一種有問題的 再這也貼出來(代碼是直接從別人那貼的)

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

問題:  重寫 compare方法這   正常的話應該有3個返回,上面這個只有2個返回,導致排完序的map在取值時會遇到問題,比如:
 sorted_map.get("A")爲null 。非要這樣排取值 可以用 getValues()和getKeys();

完善一下compare() 方法: return base.get(a)-base.get(b) ,這樣寫在後來的取值會沒有問題,但是遇到相同的value是加不進去的。 你們可以自己跑跑試試。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章