在 Java 中迭代字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18280373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterate Dictionary in Java
提问by Thomas Flynn
I've a dictionary in java:
我有一本 Java 字典:
protected Dictionary<String, Object> objects;
Now I want to get the keys of the dictionary, so that I can get the value of the key with get() in a for loop:
现在我想获取字典的键,这样我就可以在 for 循环中使用 get() 获取键的值:
for (final String key : this.objects) {
final Object value = this.objects.get(key);
But this doesn't work. :( Any idea?
但这不起作用。:( 任何的想法?
Thx Thomas
谢谢托马斯
PS: I need the key & the value both in a variable.
PS:我需要一个变量中的键和值。
采纳答案by óscar López
First things first. The Dictionary
class is way, way obsolete. You should be using a Map
instead:
先说第一件事。这Dictionary
门课已经过时了。您应该使用 aMap
代替:
protected Map<String, Object> objects = new HashMap<String, Object>();
Once that's fixed, I think this is what you meant:
一旦修复,我想这就是你的意思:
for (String key : objects.keySet()) {
// use the key here
}
If you intend to iterate over both keys and values, it's betterto do this:
如果您打算迭代键和值,最好这样做:
for (Map.Entry<String, Object> entry : objects.entrySet()) {
String key = entry.getKey();
Object val = entry.getValue();
}
回答by Daniel Gabriel
You can get the values as
您可以将这些值作为
for(final String key : this.objects.keys()){
final Object value = this.objects.get(key);
}
回答by rahul0705
java.util.Map
is the Dictionary equvivalent and below is an example on how you can iterate through each entry
java.util.Map
是等效的字典,下面是一个关于如何遍历每个条目的示例
Map<String, Object> map = new HashMap<String, Object>();
//...
for ( String key : map.keySet() ) {
}
for ( Object value : map.values() ) {
}
for ( Map.Entry<String, Object> entry : map.entrySet() ) {
String key = entry.getKey();
Object value = entry.getValue();
}
回答by Tim Shockley
If you have to use a dictionary (for example osgi felix framework ManagedService) then the following works..
如果您必须使用字典(例如 osgi felix 框架 ManagedService),那么以下工作..
public void updated(Dictionary<String, ?> dictionary)
throws ConfigurationException {
if(dictionary == null) {
System.out.println("dict is null");
} else {
Enumeration<String> e = dictionary.keys();
while(e.hasMoreElements()) {
String k = e.nextElement();
System.out.println(k + ": " + dictionary.get(k));
}
}
}