10

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?

robert_x44
  • 9,224
  • 1
  • 32
  • 37
Pure.Krome
  • 84,693
  • 113
  • 396
  • 647
  • How to iterate over a TreeMap http://stackoverflow.com/questions/1318980/how-to-iterate-over-a-treemap – Casey Jan 07 '11 at 00:36

3 Answers3

6

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.

bluish
  • 26,356
  • 27
  • 122
  • 180
Costi Ciudatu
  • 37,042
  • 7
  • 56
  • 92
5

TreeMap is probably the closest thing you're going to find.

You can iterate over the keys by calling TreeMap.keySet(); and iterating over the Set that is returned:

// assume a TreeMap<String, String> called treeMap
for(String key : treeMap.keySet())
{
    string value = treeMap[key];
}

It would be the equivalent of:

// assume a SortedDictionary called sortedDictionary
foreach(var key in sortedDictionary.Keys)
{
    var value = sortedDictionary[key];
}



You could also try the following:
// assume TreeMap<String, String> called treeMap
for (Map.Entry<String, String> entry : treeMap.entrySet())
{
    String key = entry.getKey();
    String value = entry.getValue();
}

Which is the equivalent to the following .NET code:

// assume SortedDictionary<string, string> called sortedDictionary
foreach(KeyValuePair<string, string> kvp in sortedDictionary)
{
    var key = kvp.Key;
    var value = kvp.Value;
}
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • 1
    treeMap[key] is a syntax sugar that you won't find in the current version of java. You should stick with treeMap.get(key) – Costi Ciudatu Jan 07 '11 at 00:48
1

What you need is entrySet() method of SortedMap (TreeMap).

andbi
  • 4,426
  • 5
  • 45
  • 70