How to use SortedMap interface in Java?

Bick picture Bick · Sep 15, 2011 · Viewed 177.6k times · Source

I have a

 Map<Float, MyObject>

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

Is SortedMap the best answer? TreeMap? How do I use it?

I only create the map once and replace the MyObject frequently using myMap.put() and myMap.get().

Answer

Barth picture Barth · Sep 15, 2011

I would use TreeMap, which implements SortedMap. It is designed exactly for that.

Example:

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());
}

See the Java tutorial page for SortedMap.
And here a list of tutorials related to TreeMap.