Java中的.NET SortedDictionary相当于什么?

Pur*_*ome 10 .net java enumeration sorteddictionary data-structures

如果.NET有一个SortedDictionary对象......请问Java中的这个是什么?我还需要能够Enumeration在Java代码中检索(元素)..因此我可以迭代所有键.

我在想它是一个TreeMap?但是,我不认为有Enumeration这样的暴露?

有任何想法吗?

Cos*_*atu 6

TreeMap将是正确的选择.至于所有键(或值)的集合,任何Map公开keySet()values().

编辑(用代码标签回答你的问题).假设你有一个Map<String, Object>:

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

您也可以使用entrySet()而不是keySet()values()为了遍历key-> value对.


Jus*_*ner 5

TreeMap 可能是你最接近的东西.

您可以通过调用TreeMap.keySet();并迭代返回的Set来迭代键:

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

它相当于:

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



您还可以尝试以下方法:

// assume TreeMap<String, String> called treeMap
for (Map.Entry<String, String> entry : treeMap.entrySet())
{
    String key = entry.getKey();
    String value = entry.getValue();
}
Run Code Online (Sandbox Code Playgroud)

这相当于以下.NET代码:

// assume SortedDictionary<string, string> called sortedDictionary
foreach(KeyValuePair<string, string> kvp in sortedDictionary)
{
    var key = kvp.Key;
    var value = kvp.Value;
}
Run Code Online (Sandbox Code Playgroud)