首頁  >  文章  >  Java  >  如何使用 JSTL 迭代 HashMap 中的 ArrayList?

如何使用 JSTL 迭代 HashMap 中的 ArrayList?

Susan Sarandon
Susan Sarandon原創
2024-10-24 16:51:02705瀏覽

How to Iterate an ArrayList Inside a HashMap Using JSTL?

使用JSTL 迭代HashMap 中的ArrayList

在Web 開發中,JSTL(JavaServer Pages 標準標記庫)提供了一組標記來簡化JSP 中的常見任務( Java 伺服器頁面)。其中一項任務是迭代資料結構。

要迭代 HashMap 及其中包含的 ArrayList,您可以使用 JSTL 的 ;標籤。它支援循環遍歷集合和映射:

對於數組和集合,var為您提供當前迭代的項目。

<code class="html"><c:forEach items="${collectionOrArray}" var="item">
    Item = ${item}<br>
</c:forEach></code>

對於映射 , var 給你一個 Map.Entry 對象,它有 getKey() 和 getValue() 方法。

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

由於entry.value是一個列表,所以也迭代它:

<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>

varStatus 屬性透過追蹤循環的迭代狀態來增強可讀性。

下面類似的Java 實作有助於理解該過程:

<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>

有關進一步參考,請查看以下資源:

  • [在JSP 中循環HashMap](https://stackoverflow.com/questions/11085751/how-to-loop-through-a-hashmap-in-jsp)
  • [使用MVC 和DAO 在JSP 中顯示JDBC 結果集] (https://stackoverflow.com/questions/23612802/show-jdbc-resultset-in-html-in-jsp-page-using-mvc-and-dao-pattern )
  • [在JSTL 中循環循環指定次數](https://stackoverflow.com/questions/1054242/how-to-loop-over-something-a-specified-number-of-times- in-jstl)

以上是如何使用 JSTL 迭代 HashMap 中的 ArrayList?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn