TreeMap按照value進行排序


TreeMap底層是根據紅黑樹的數據結構構建的,默認是根據key的自然排序來組織(比如integer的大小,String的字典排序)。所以,TreeMap只能根據key來排序,是不能根據value來排序的(否則key來排序根本就不能形成TreeMap)。


今天有個需求,就是要根據treeMap中的value排序。所以網上看了一下,大致的思路是把TreeMap的EntrySet轉換成list,然后使用Collections.sor排序。代碼:

[java] view plain copy
  1. public static void sortByValue() {  
  2.         Map<String,String> map = new TreeMap<String,String>();  
  3.         map.put("a", "dddd");  
  4.         map.put("d", "aaaa");  
  5.         map.put("b", "cccc");  
  6.         map.put("c", "bbbb");  
  7.           
  8.         List<Entry<String, String>> list = new ArrayList<Entry<String, String>>(map.entrySet());  
  9.           
  10.         Collections.sort(list,new Comparator<Map.Entry<String,String>>() {  
  11.             //升序排序  
  12.             public int compare(Entry<String, String> o1, Entry<String, String> o2) {  
  13.                 return o1.getValue().compareTo(o2.getValue());  
  14.             }  
  15.         });  
  16.           
  17.         for (Entry<String, String> e: list) {  
  18.             System.out.println(e.getKey()+":"+e.getValue());  
  19.         }  
  20.     }  


運行結果: d:aaaa
c:bbbb
b:cccc
a:dddd


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM