Iterate over elements of List and Map using JSTL <c:forEach> tag

foreach, hashmap, jsp, jstl, list

Solution

Suppose `${list}` points to a `List<Object>`, then the following

<c:forEach items="${list}" var="item">
    ${item}<br>
</c:forEach>

does basically the same as as following in "normal Java":

for (Object item : list) {
    System.out.println(item);
}

If your `${list}` is a `List<Person>` where `Person` is a Javabean having `name` and `email` properties represented by `getName()` and `getEmail()` getter methods, then the following

<c:forEach items="${list}" var="person">
    ${person.name}<br>
    ${person.email}<br>
</c:forEach>

does basically the same as as following in "normal Java":

for (Person person : list) {
    System.out.println(person.getName());
    System.out.println(person.getEmail());
}

If you have a `List<Map<K, V>>` instead, then the following

<c:forEach items="${list}" var="map">
    <c:forEach items="${map}" var="entry">
        ${entry.key}<br>
        ${entry.value}<br>
    </c:forEach>
</c:forEach>

does basically the same as as following in "normal Java":

for (Map<K, V> map : list) {
    for (Entry<K, V> entry : map.entrySet()) {
        System.out.println(entry.getKey());
        System.out.println(entry.getValue());
    }
}

The `key` and `value` are here not special methods or so. They are actually getter methods of `Map.Entry` object (click at the blue `Map.Entry` link to see the API doc). In EL (Expression Language) you can use the `.` dot operator to access getter methods using "property name" (the getter method name without the `get` prefix), all just according the Javabean specification.

See also:

- Places where JavaBeans are used?

- Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern

- javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

Problem

If I have a JSF backing bean return an object of type ArrayList, I should be able to use `<c:foreach>` to iterate over the elements in the list. Each element contains a map and although the question of how to access the map content through JSTL has been answered here, if I pass an array of such maps, I can't find how to iterate over them and still access the map content using JSTL. There's documentation which refers to simple iterators but not to those whose items are themselves maps. If anyone can give me a simple example of how a java List is iterated over in JSP I'd be massively appreciative. Mark

Original source

Related problems