views:

1659

answers:

2

I am having map like this,

Map<Integer,ArrayList<Object>> myMap = new LinkedHashMap<Integer,ArrayList<Object>>();

Now i have to iterate this Map and then the ArrayList inside the map. How can i do this using jstl.

+2  A: 

Did you try something like this?

<c:forEach var='item' items='${map}'>
    <c:forEach var='arrayItem' items='${item.value}' />
      ...
    </c:forEach>
</c:forEach>
dcp
And of course, you might want to output `${item.key}` between the two foreach statements.
R. Bemrose
+3  A: 

You can use JSTL c:forEach tag to iterate over collections and maps. In case of maps, every iteration will give you a Map.Entry which in turn has getKey() and getValue() methods.

Here's a basic example:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

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

In your particular case, the ${entry.value} is actually a List, thus you need to iterate over it as well:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:forEach items="${map}" var="entry">
    Key = ${entry.key}, values = 
    <c:forEach items="${entry.value}" var="item" varStatus="loop">
        ${item} ${!loop.last ? ', ' : ''}
    </c:forEach><br>
<c:forEach>

The varStatus is there just for convenience ;)

To understand better what's all going on here, here's a raw Java translation:

for (Entry<String, List<Object>> entry : map.entrySet()) {
    out.print("Key = " + entry.getKey() + ", values = ");
    for (Iterator<Object> iter = entry.getValue().iterator(); iter.hasNext();) {
        Object item = iter.next();
        out.print(item + (iter.hasNext() ? ", " : ""));
    }
    out.println();
}
BalusC
i like the way u used '${!loop.last ? ', ' : ''}' :D
Rakesh Juyal
You can find more methods here: http://java.sun.com/products/jsp/jstl/1.1/docs/api/javax/servlet/jsp/jstl/core/LoopTagStatus.html The `${loop.index}`, `${loop.first}` and `${loop.last}` are most useful here.
BalusC