2011-09-15 58 views
46

我有一個如何在Java中使用SortedMap接口?

map<Float, MyObject> 

什麼是持有根據浮動排序的地圖的最佳方式。
SortedMap最佳答案? TreeMap?我如何使用它?

(我只有一次創建地圖和更換MyObject頻繁使用 myMap.put()myMap.get()

+0

但SortedMap是一個接口。 TreeMap實現SortedMap。 –

+0

查看'@ user157196'發表的答案這裏http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java – Bitmap

+0

尋找Tom Jefferys'回答 – JohnnyLambada

回答

59

我會用TreeMap,它實現SortedMap。它正是爲此而設計的。

實施例:

Map<Integer, String> map = new TreeMap<Integer, String>(); 

// Add Items to the TreeMap 
map.put(1, "One"); 
map.put(2, "Two"); 
map.put(3, "Three"); 

// Iterate over them 
for (Map.Entry<Integer, String> entry : map.entrySet()) { 
    System.out.println(entry.getKey() + " => " + entry.getValue()); 
} 

Java tutorial page for SortedMap
here a list of tutorials與TreeMap相關。

+0

爲什麼你要做'新的整數(n)'而不是僅僅整數? –

+0

@Adam_G沒有特別的理由,我想當我寫這個答案時,我不習慣自動裝箱(?)。 – Barth

3

TreeMap的,這是SortedMap接口的實現,是可行的。

如何使用它?

Map<Float, MyObject> map = new TreeMap<Float, MyObject>(); 
34

一個TreeMap可能是這樣做的最直接的方法。您完全像普通的地圖一樣使用它。

Map<Float,String> mySortedMap = new TreeMap<Float,MyObject>(); 
    // Put some values in it 
    mySortedMap.put(1.0f,"One"); 
    mySortedMap.put(0.0f,"Zero"); 
    mySortedMap.put(3.0f,"Three"); 

    // Iterate through it and it'll be in order! 
    for(Map.Entry<Float,String> entry : mySortedMap.entrySet()) { 
     System.out.println(entry.getValue()); 
    } // outputs Zero One Three 

這是值得的API文檔考慮看看,http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html看到你可以用它做什麼。

+0

恕我直言,這一個比接受的答案更好 – Kawu

2

TreeMap按關鍵自然排序排序。密鑰應該實現Comparable或兼容Comparator(如果您將一個實例傳遞給構造函數)。在你的情況下,Float已經實現了Comparable,所以你不必做任何特別的事情。

您可以撥打keySet以升序檢索所有密鑰。

9

您可以使用TreeMap中,其內部實現下面的SortedMap是例如

通過升序排列排序:

//Create the map and provide the comparator as a argument 
    Map<Integer,String> dscsortedMAP = new TreeMap<Integer,String>(new Comparator<Integer>() 
    { 
     @Override 
     public int compare(Integer o1, Integer o2) {     
      return o2.compareTo(o1); 
     } 
    }); 
    dscsortedMAP.putAll(ascsortedMAP); 

     for(Map.Entry<Integer, String> mapData : dscsortedMAP.entrySet()) { 
     System.out.println("Key : " +mapData.getKey()+" Value : "+mapData.getValue()); 
     } 

爲:按降序排序排序

Map<Integer,String> ascsortedMAP = new TreeMap<Integer,String>(); 

    ascsortedMAP.put(8, "name8"); 
    ascsortedMAP.put(5, "name5"); 
    ascsortedMAP.put(15, "name15"); 
    ascsortedMAP.put(35, "name35"); 
    ascsortedMAP.put(44, "name44"); 
    ascsortedMAP.put(7, "name7"); 
    ascsortedMAP.put(6, "name6"); 

    for(Map.Entry<Integer, String> mapData : ascsortedMAP.entrySet()) { 
    System.out.println("Key : " +mapData.getKey()+ "Value : "+mapData.getValue()); 
    } 

有關SortedMAP的更多信息,請參閱http://examples.javacodegeeks.com/core-java/util/treemap/java-sorted-map-example/

+0

我更喜歡這個答案,因爲它是通過使用比較器來設計SortedMap的設計 – CodeToLife