How to iterate over all elements in a Java Map

by moyuhappy on 2008-08-05 15:22:05

In JDK 1.4:

```java

Map map = new HashMap();

Iterator it = map.entrySet().iterator();

while (it.hasNext()) {

Map.Entry entry = (Map.Entry) it.next();

Object key = entry.getKey();

Object value = entry.getValue();

}

```

In JDK 1.5, using the new feature: the For-Each loop:

```java

Map map = new HashMap();

for (Map.Entry entry : map.entrySet()) {

Object key = entry.getKey();

Object value = entry.getValue();

}

```

The for-each loop simplifies the iteration over the collection and improves code readability.