In web development, JSTL (JavaServer Pages Standard Tag Library) provides a set of tags for simplifying common tasks in JSP (JavaServer Pages). One such task is iterating over data structures.
To iterate over a HashMap and the ArrayLists contained within it, you can use JSTL's
For arrays and collections, var gives you the currently iterated item.
<code class="html"><c:forEach items="${collectionOrArray}" var="item"> Item = ${item}<br> </c:forEach></code>
For maps, var gives you a Map.Entry object, which has getKey() and getValue() methods.
<code class="html"><c:forEach items="${map}" var="entry"> Key = ${entry.key}, value = ${entry.value}<br> </c:forEach></code>
Since the entry.value is a list, iterate over it as well:
<code class="html"><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></code>
The varStatus attribute enhances readability by tracking the loop's iteration status.
A similar Java implementation below helps understand the process:
<code class="java">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(); }</code>
For further reference, review the following resources:
The above is the detailed content of How to Iterate an ArrayList Inside a HashMap Using JSTL?. For more information, please follow other related articles on the PHP Chinese website!