2011-09-15 102 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