Home > Java > javaTutorial > How to Iterate over a HashMap and ArrayLists within it using JSTL

How to Iterate over a HashMap and ArrayLists within it using JSTL

Barbara Streisand
Release: 2024-10-24 11:16:29
Original
1013 people have browsed it

How to Iterate over a HashMap and ArrayLists within it using JSTL

Iterating an ArrayList within a HashMap using JSTL

In Java, a HashMap is a data structure that stores key-value pairs, where the keys are unique identifiers for the values. Often, it's necessary to iterate through both the HashMap and the ArrayLists stored within its values.

To do this using JSTL, we can employ the tag. This tag is designed to iterate over collections and maps.

Iterating over a HashMap

For a HashMap, the tag iterates over the key-value pairs, providing access to both the key and the value in each iteration.

<code class="java"><c:forEach items="${myMap}" var="entry">
    Key = ${entry.key}<br>
    Value = ${entry.value}<br>
</c:forEach></code>
Copy after login

Iterating over an ArrayList within a HashMap

Since the values in the HashMap are ArrayLists, we need to iterate over them within the outer loop.

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

In this example, the inner loop uses the tag again to iterate over the ArrayList. The varStatus attribute allows us to check if the current iteration is the last one, which is useful for adding appropriate delimiters like commas.

Additional Resources

  • [Looping through a HashMap in JSP](https://stackoverflow.com/questions/9966200/howto-loop-through-hashmap-in-jsp)
  • [Using in JSTL](https://docs.oracle.com/javaee/7/api/javax/servlet/jsp/jstl/core/ForeachTag.html)

The above is the detailed content of How to Iterate over a HashMap and ArrayLists within it 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