Home >Java >javaTutorial >How to Iterate over an ArrayList within a HashMap in JSTL?

How to Iterate over an ArrayList within a HashMap in JSTL?

DDD
DDDOriginal
2024-10-24 16:13:02289browse

How to Iterate over an ArrayList within a HashMap in JSTL?

Iterating an ArrayList inside a HashMap in JSTL

In Java Server Pages (JSP), the Java Standard Tag Library (JSTL) provides convenient tags for iterating over data structures. This includes iterating over maps, where each key-value pair is stored as a Map.Entry object.

To iterate over both the keys and values of a HashMap, including any ArrayLists stored as values, you can use nested tags as follows:

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

<c:forEach items="${myMap}" var="entry">
    <span>Key: ${entry.key}</span>
    
    <c:forEach items="${entry.value}" var="item" varStatus="loop">
        <span>Value: ${item}</span>
        <c:if test="${!loop.last}">, </c:if>
    </c:forEach>
    
    <br>
</c:forEach></code>

This code iterates over the myMap HashMap and, for each key-value pair, outputs the key followed by a list of values in the corresponding ArrayList. The varStatus attribute is used to determine whether the current item is the last in the list, so that a comma is added between items only if they are not the last.

Additional Notes:

  • For more complex scenarios, you may need to cast the entry.key and entry.value objects to the appropriate types.
  • The nested tag iterates over the ArrayList as a whole, so if you need to access individual elements within the ArrayList, you'll need to use additional logic.

The above is the detailed content of How to Iterate over an ArrayList within a HashMap in JSTL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn