Java Map按鍵(Key)排序和按值(Value)排序

來源:互聯網
上載者:User

標籤:cti   iterator   link   ons   代碼   super   new   str   收藏   

Map排序的方式有很多種,兩種比較常用的方式:按鍵排序(sort by key), 按值排序(sort by value)。
1、按鍵排序
jdk內建的java.util包下的TreeMap<K,V>既可滿足此類需求,向其構造方法 TreeMap(Comparator<? super K> comparator)  傳入我們自訂的比較子即可實現按鍵排序。

 

Java代碼  
  1. public class MapSortDemo {  
  2.     public static void main(String[] args) {  
  3.         Map<String, String> map = new TreeMap<String, String>();  
  4.         map.put("KFC", "kfc");  
  5.         map.put("WNBA", "wnba");  
  6.         map.put("NBA", "nba");  
  7.         map.put("CBA", "cba");  
  8.         Map<String, String> resultMap = sortMapByKey(map);    //按Key進行排序  
  9.         for (Map.Entry<String, String> entry : resultMap.entrySet()) {  
  10.             System.out.println(entry.getKey() + " " + entry.getValue());  
  11.         }  
  12.     }  
  13.       
  14.     /** 
  15.      * 使用 Map按key進行排序 
  16.      * @param map 
  17.      * @return 
  18.      */  
  19.     public static Map<String, String> sortMapByKey(Map<String, String> map) {  
  20.         if (map == null || map.isEmpty()) {  
  21.             return null;  
  22.         }  
  23.         Map<String, String> sortMap = new TreeMap<String, String>(new MapKeyComparator());  
  24.         sortMap.putAll(map);  
  25.         return sortMap;  
  26.     }  
  27. }  
  28.   
  29. //比較子類  
  30. public class MapKeyComparator implements Comparator<String>{  
  31.     public int compare(String str1, String str2) {  
  32.         return str1.compareTo(str2);  
  33.     }  
  34. }  

 2、按值排序
按值排序就相對麻煩些了,貌似沒有直接可用的資料結構能處理類似需求,需要我們自己轉換一下。
Map本身按值排序是很有意義的,很多場合下都會遇到類似需求,可以認為其值是定義的某種規則或者權重。

 

原理:將待排序Map中的所有元素置於一個列表中,接著使用Collections的一個靜態方法 sort(List<T> list, Comparator<? super T> c) 
來排序列表,同樣是用比較子定義比較規則。排序後的列表中的元素再依次裝入Map,為了肯定的保證Map中元素與排序後的List中的元素的順序一致,使用了LinkedHashMap資料類型。

Java代碼  
    1. 實現代碼  
    2.   
    3. public class MapSortDemo {  
    4.     public static void main(String[] args) {  
    5.         Map<String, String> map = new TreeMap<String, String>();  
    6.         map.put("KFC", "kfc");  
    7.         map.put("WNBA", "wnba");  
    8.         map.put("NBA", "nba");  
    9.         map.put("CBA", "cba");  
    10.         Map<String, String> resultMap = sortMapByValue(map); //按Value進行排序  
    11.         for (Map.Entry<String, String> entry : resultMap.entrySet()) {  
    12.             System.out.println(entry.getKey() + " " + entry.getValue());  
    13.         }  
    14.     }  
    15.       
    16.     /** 
    17.      * 使用 Map按value進行排序 
    18.      * @param map 
    19.      * @return 
    20.      */  
    21.     public static Map<String, String> sortMapByValue(Map<String, String> map) {  
    22.         if (map == null || map.isEmpty()) {  
    23.             return null;  
    24.         }  
    25.         Map<String, String> sortedMap = new LinkedHashMap<String, String>();  
    26.         List<Map.Entry<String, String>> entryList = new ArrayList<Map.Entry<String, String>>(map.entrySet());  
    27.         Collections.sort(entryList, new MapValueComparator());  
    28.         Iterator<Map.Entry<String, String>> iter = entryList.iterator();  
    29.         Map.Entry<String, String> tmpEntry = null;  
    30.         while (iter.hasNext()) {  
    31.             tmpEntry = iter.next();  
    32.             sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());  
    33.         }  
    34.         return sortedMap;  
    35.     }  
    36. }  
    37.   
    38. //比較子類  
    39. public class MapValueComparator implements Comparator<Map.Entry<String, String>> {  
    40.     public int compare(Entry<String, String> me1, Entry<String, String> me2) {  
    41.         return me1.getValue().compareTo(me2.getValue());  
    42.     }  
    43. }  

Java Map按鍵(Key)排序和按值(Value)排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.