Tuesday, June 01, 2004

Map iterations using c:forEach

Using the c:forEach custom tag, it is easy to iterate over collections including map's.
Altough you have to keep in mind that the resulting value is a MapItem.

The MapItem has 2 properties named key and value.
These properties can be treated as javabeans theirselves, hence its properties being retrieved according to the javabean specification.
Hereunder follows a sample that iterates over a map, the key is of type String and the value of a type that complies to the javabean specification:

<table>
<c:forEach var="item" items="myMap">
<tr>
<td>
<c:out value="${item.key}"/>
</td>
<td>
<c:out value="${item.value.givenName}"/>
</td>
<td>
<c:out value="${item.value.surName}"/>
</td>
</tr>
</c:forEach>
</table>
The output of the above sample is:

1JohnDoe
2JaneDoe
3Johnny jr.Doe