java對map中value的排序

  1. package Map;   
  2.   
  3. import java.util.ArrayList;   
  4. import java.util.Collections;   
  5. import java.util.Comparator;   
  6. import java.util.List;   
  7. import java.util.Map;   
  8. import java.util.Map.Entry;   
  9. import java.util.TreeMap;   
  10.   
  11. public class SortMap {   
  12.        public static void main(String[] args) {   
  13.       Map map=new TreeMap ();   
  14.       map.put("圖書" , 4);   
  15.       map.put("音像" , 6);   
  16.       map.put("素材" , 9);   
  17.       map.put("音樂" , 8);   
  18.       map.put("影視" , 7);   
  19.       map.put("動漫" , 4);   
  20.       map.put("歌曲" , 3);   
  21.       map.put("圖片" , 2);   
  22.       map.put("圖標" , 6);   
  23.       ArrayList<Map.Entry<String,Integer>> entries= sortMap(map);   
  24.       forint i=0;i<5;i++){   
  25.             System. out.print(entries.get(i).getKey()+":" +entries.get(i).getValue());   
  26.       }   
  27.       }   
  28.     public static ArrayList<Map.Entry<String,Integer>> sortMap(Map map){   
  29.      List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());   
  30.      Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {   
  31.          public int compare(Map.Entry<String, Integer> obj1 , Map.Entry<String, Integer> obj2) {   
  32.              return obj2.getValue() - obj1.getValue();   
  33.          }   
  34.      });   
  35.       return (ArrayList<Entry<String, Integer>>) entries;   
  36.     }   
  37. }  
  38. 此時是按照降序排序,如果想升序排序,則Comparator的 返回 改爲obj1.getValue() - obj2.getValue();即可


    總結:由於TreeMap主要是針對key進行默認排序的,但是有的時候我們需要對value進行排序,這時候主要採取的策略是 將map變爲List,然後利用Collections.sort進行排序,同時重寫Comparator方法,即可。
發佈了31 篇原創文章 · 獲贊 5 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章