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

7 comments:

I am a ComplexNumber said...

Thanks! This is highly helpful

Anonymous said...

Thank you for your code snippet.
Very helpful.

Anonymous said...

Very clever advice.
Now my JSP web working fine.
Thanks from Europe.

will824 said...

Simple but extremelly useful. Thanks!

Tomas said...

Right to the spot. Exactly what I needed. Big Thanks.

Stranger said...

Thanks, was struggling with the same problem for quite a while. :-)

Sanket said...

Thank you very much for the advice. I can see that this post is pretty old but still very much relevant and useful.