java中對map根據value進行排序(Integer、String均使用)

1、聲明一個hashmap對象

Map<Integer, Integer> map = new HashMap<Integer, Integer>();

2、put數據

3、通過ArrayList構造函數把map.entrySet()轉換成list

List<Map.Entry<Integer, Integer>> mappingList = new ArrayList<Map.Entry<Integer, Integer>>(map.entrySet());

4、通過比較器進行比較排序 

Collections.sort(mappingList, new Comparator<Map.Entry<Integer, Integer>>(){
    public int compare(Map.Entry<Integer, Integer> mapping1, Map.Entry<Integer, Integer> mapping2){
        return mapping1.getValue().compareTo(mapping2.getValue());
    }
});

5、查看

for(Map.Entry<String,String> mapping:mappingList){
   System.out.println(mapping.getKey()+":"+mapping.getValue());
  }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章