What's the equivalent to a .NET SortedDictionary, in Java?

Pure.Krome picture Pure.Krome · Jan 7, 2011 · Viewed 7.8k times · Source

If .NET has a SortedDictionary object ... what is this in Java, please? I also need to be able to retrieve an Enumeration (of elements), in the Java code .. so I can just iterate over all the keys.

I'm thinking it's a TreeMap ? But I don't think that has an Enumeration that is exposed?

Any ideas?

Answer

Costi Ciudatu picture Costi Ciudatu · Jan 7, 2011

TreeMap would be the right choice. As for the Collection of all the keys (or values), any Map exposes keySet() and values().

EDIT (to answer your question with code tags). Assuming you have a Map<String, Object>:

for (String key : map.keySet()) {
     System.out.println(key); // prints the key
     System.out.println( map.get(key) ); // prints the value
}

You can also use entrySet() instead of keySet() or values() in order to iterate through the key->value pairs.