Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate Dictionary in Java

I've a dictionary in 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 (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.

like image 300
Thomas Flynn Avatar asked Aug 16 '13 19:08

Thomas Flynn


1 Answers

First things first. The Dictionary class is way, way obsolete. You should be using a Map instead:

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 better to do this:

for (Map.Entry<String, Object> entry : objects.entrySet()) {
    String key = entry.getKey();
    Object val = entry.getValue();
}
like image 198
Óscar López Avatar answered Sep 25 '22 00:09

Óscar López