Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top