Jeb Jeb - 1 year ago 86
Java Question

How to use SortedMap Interface in Java?

I have a

map<Float, MyObject>

What is the best way to hold 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(), myMap.get)

Answer Source

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


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

// Add Items to the TreeMap
map.put(new Integer(1), "One");
map.put(new Integer(2), "Two");
map.put(new Integer(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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download