如何在Java中使用SortedMap接口?

Bic*_*ick 64 java sortedmap

我有一个

 Map<Float, MyObject>
Run Code Online (Sandbox Code Playgroud)

根据浮点数保持地图排序的最佳方法是什么?

SortedMap最好的答案吗?TreeMap?我该如何使用它?

我只创建一次地图并替换MyObject频繁使用myMap.put()myMap.get().

Bar*_*rth 85

我会用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());
}
Run Code Online (Sandbox Code Playgroud)

请参阅SortedMapJava教程页面.
这里的教程列表相关TreeMap的.


Tom*_*rys 43

TreeMap可能是最简单的方法.你使用它就像普通的Map一样.

    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 
Run Code Online (Sandbox Code Playgroud)

值得一看的是api docs,http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html,看看你还能用它做些什么.


Lea*_*ner 14

你可以使用TreeMap在内部实现下面的SortedMap就是例子

按升序排序:

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

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

  for (Entry<Float, String> mapData : ascsortedMAP.entrySet()) {
    System.out.println("Key : " + mapData.getKey() + "Value : " + mapData.getValue());
  }
Run Code Online (Sandbox Code Playgroud)

按降序排序:

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

有关SortedMAP的更多信息,请阅读http://examples.javacodegeeks.com/core-java/util/treemap/java-sorted-map-example/

  • 我更喜欢这个答案,因为它通过使用比较器来制作 SortedMap 的设计目的 (2认同)