How to use SortedMap interface in Java?

前端 未结 6 622
谎友^
谎友^ 2020-12-01 02:03

I have a

 Map

What is the best way to keep the map sorted according to the float?

Is SortedMap

6条回答
  •  半阙折子戏
    2020-12-01 02:11

    A TreeMap is probably the most straightforward way of doing this. You use it exactly like a normal Map. i.e.

    Map mySortedMap = new TreeMap();
    // 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 entry : mySortedMap.entrySet()) {
        System.out.println(entry.getValue());
    } // outputs Zero One Three 
    

    It's worth taking a look at the API docs, http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html to see what else you can do with it.

提交回复
热议问题