简体   繁体   中英

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

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?

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.

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 SortedDictionary<string, string> called sortedDictionary
foreach(KeyValuePair<string, string> kvp in sortedDictionary)
{
    var key = kvp.Key;
    var value = kvp.Value;
}

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

你需要的是SortedMap(TreeMap)的entrySet()方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM