Home > Java > javaTutorial > How to Iterate over ArrayLists in HashMaps using JSTL?

How to Iterate over ArrayLists in HashMaps using JSTL?

Mary-Kate Olsen
Release: 2024-10-24 11:31:02
Original
658 people have browsed it

How to Iterate over ArrayLists in HashMaps using JSTL?

Iterating ArrayLists within HashMaps using JSTL

Question:

Iterating over a HashMap itself is straightforward using JSTL's tag. However, how do you iterate over the ArrayList values associated with each key in the HashMap?

Solution:

JSTL's tag provides flexibility in iterating over different data structures, including maps.

Iterating the Map:

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

<c:forEach items="${myMap}" var="entry"></code>
Copy after login

This iterates over the map's entries, where each entry is a Map.Entry object with getKey() and getValue() methods.

Iterating the ArrayList:

To access the ArrayList associated with an entry, use entry.getValue(), which returns the list as an object. You can then iterate over the list as follows:

<code class="jsp"><c:forEach items="${entry.value}" var="item"></code>
Copy after login

Combined Example:

<code class="jsp"><c:forEach items="${myMap}" var="entry">
    Key: ${entry.key}<br>
    Values:<br>
    <c:forEach items="${entry.value}" var="item">
        ${item}
        ${!loop.last ? ', ' : ''}
    </c:forEach><br>
</c:forEach></code>
Copy after login

This example iterates over the map, retrieving the ArrayList associated with each key. It then iterates over the ArrayList, displaying the key and values.

Additional Notes:

  • The varStatus object provides additional information during the iteration, such as the current index.
  • For a better understanding, refer to the provided Java translation of the JSTL code.

The above is the detailed content of How to Iterate over ArrayLists in HashMaps using JSTL?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template