我想在Java中遍历字典中的每个项。为了澄清我的意图,这是C#代码:
Dictionary<string, Label> LableList = new Dictionary<string, Label>();
foreach (KeyValuePair<string, Label> z in LabelList);
我不知道如何在Java中实现这个,例如我做了这个:
for(Object z: dic)
但它说它不可迭代。请给予建议......
我想在Java中遍历字典中的每个项。为了澄清我的意图,这是C#代码:
Dictionary<string, Label> LableList = new Dictionary<string, Label>();
foreach (KeyValuePair<string, Label> z in LabelList);
我不知道如何在Java中实现这个,例如我做了这个:
for(Object z: dic)
但它说它不可迭代。请给予建议......
Map<String, Label>
,它是Java内置的字典结构。Java不允许直接迭代Map
(即它没有实现Iterable
),因为这会导致你要迭代什么变得模糊不清。
这只是选择通过键、值或条目(两者兼备)进行迭代的问题。
例如:
Map<String, Label> map = new HashMap<String, Label>();
//...
for ( String key : map.keySet() ) {
}
for ( Label value : map.values() ) {
}
for ( Map.Entry<String, Label> entry : map.entrySet() ) {
String key = entry.getKey();
Label value = entry.getValue();
}
你的 C# 代码似乎与迭代条目的方式相同(最后一个示例)。
java.util.Map
是一个类似于字典的数据结构,下面是一个遍历每个元素的示例:
for(Map.Entry<K, V> e : map.entrySet())
{
System.out.println(e.getKey()+": "+e.getValue());
}
您最好使用这个:
for (String key : LableList.keys()) {
Label value = LableList.get(key);
// do what you wish with key and value here
}
然而,在Java中,最好不要像在.NET中那样使用Dictionary,而是使用其中一个Map子类,例如HashMap。您可以通过以下方式遍历其中一个:
for (Entry<String, Label> e : myMap.entrySet()) {
// Do what you wish with e.getKey() and e.getValue()
}
我们建议您不要在官方javadoc中使用字典。
我正在尝试将一个HashMap(a)的内容添加到另一个HashMap(b)中。
我发现可以通过以下方式简单地遍历HashMap a:
a.forEach((k, v) -> b.put(k, v));
对于那些想知道如何在无法使用 Map 的情况下迭代字典的人,例如在 Java 中使用 SeviceReferences:
Java 8+
dict.keys().asIterator().forEachRemaining((key -> {
value = dict.get(key);
//your code here using the key/value pair.
});
HashMap
- 它也实现了你需要让可迭代工作的新函数。 - Voo