Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach loop in java for Dictionary

I want to go through every items in a dictionary in java. to clarify what I want to do, this is the C# code

Dictionary<string, Label> LableList = new Dictionary<string, Label>();
foreach (KeyValuePair<string, Label> z in LabelList);

I don't know how to do this is java, for example I did this

for(Object z: dic)

but it says it's not iterable. Please advise......

like image 530
Daniel Avatar asked Feb 21 '12 03:02

Daniel


2 Answers

I'm assuming you have a Map<String, Label> which is the Java built-in dictionary structure. Java doesn't let you iterate directly over a Map (i.e. it doesn't implement Iterable) because it would be ambiguous what you're actually iterating over.

It's just a matter of choosing to iterate through the keys, values or entries (both).

e.g.

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

Your C# code seems to be the same as iterating over the entries (the last example).

like image 176
Mark Peters Avatar answered Nov 09 '22 22:11

Mark Peters


Your best bet is to use this:

for (String key : LableList.keys()) {
    Label value = LableList.get(key);

    // do what you wish with key and value here
}

In Java however, a better bet is to not use Dictionary as you would in .NET but to use one of the Map subclasses, e.g. HashMap. You can iterate through one of these like this:

for (Entry<String, Label> e : myMap.entrySet()) {
    // Do what you wish with e.getKey() and e.getValue()
}

You are also advised against using Dictionary in the official javadoc.

like image 29
Fritz H Avatar answered Nov 09 '22 21:11

Fritz H