2012-08-14 145 views
0

我試圖找到一個類似於LinkedHashMap的結構,通過它的值對它進行排序。 我需要能夠更新這些值。 我會經常檢查訂單,所以我需要一個避免每次對地圖進行排序的解決方案。LinkedHashMap按值排序

是這樣的:

DynamicSortedMap<String,Integer> map = new DynamicSortedMap<String,Integer>(); 
map.put("key1",4); 
map.put("key2",3); 
map.put("key3",6); 
System.out.println("Map: "+map); 
map.update("key1",1); 
System.out.println("Update:"+map); 

輸出:

Map: {key3=6, key1=4, key2=3} 
Update: {key3=6, key2=3, key1=1} 

是否有允許這種任何stucture? 如果沒有,如何做到這一點的任何想法?

感謝您的幫助,

+0

「LinkedHashMap」按插入而不是值排序。你要找的是['TreeMap'](http://docs.oracle.com/javase/6/docs/api/java/util/TreeMap.html)。 – 2012-08-14 12:26:49

+0

我回應了TreeMap的建議。 LinkedHashMap的哪些功能使您可以在其他地圖上選擇它? – 2012-08-14 12:28:08

+0

'TreeMap'按鍵排序(但我認爲OP就是這樣)。 :) – dacwe 2012-08-14 12:28:15

回答

1

我認爲你正在尋找類似TreeMap的,這是關鍵的排序:

SortedMap<String, Integer> map = new TreeMap<String, Integer>(); 
+0

是否可以按值排序樹圖? – magodiez 2012-08-14 12:45:12

+0

是 - > http://stackoverflow.com/questions/2864840/treemap-sort-by-value – tostao 2012-08-14 13:14:31

0

即使LinkedHashMap的其實可能是一個很好的基礎很不幸在操作迭代次序方面非常有限。我認爲apache common-collections你更好。

0
class SortValueMap extends HashMap<String,Integer>{ 

    @Override 
    public Set<Entry<String,Integer>> entrySet() { 
     List<Entry<String,Integer>> entries = new ArrayList<Entry<String,Integer>>(super.entrySet()); 
     Collections.sort(entries, new Comparator<Entry<String,Integer>>(){ 

      @Override 
      public int compare(Map.Entry<String,Integer> o1, Map.Entry<String,Integer> o2) { 
       return o1.getValue().compareTo(o2.getValue()); 
      }}); 
     return new LinkedHashSet<Entry<String,Integer>>(entries); 
    } 
} 
    ... 
SortValueMap map = new SortValueMap(); 
map.put("key1",4); 
map.put("key2",3); 
map.put("key3",6); 
map.put("key4",1); 
System.out.println("Map: "+map);