本文介绍了如何使用迭代JSTL一个HashMap里面一个ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有地图这样的,

Map<Integer,ArrayList<Object>> myMap = new LinkedHashMap<Integer,ArrayList<Object>>();

现在我不得不重复这个地图,然后在地图内的ArrayList。我怎样才能做到这一点使用JSTL?

Now I have to iterate this Map and then the ArrayList inside the map. How can I do this using JSTL?

推荐答案

您可以使用的遍历数组,集合和地图。

You can use JSTL <c:forEach> tag to iterate over arrays, collections and maps.

在数组和集合的情况下,每个迭代的 VAR 会给你不仅仅是当前迭代马上项。

In case of arrays and collections, every iteration the var will give you just the currently iterated item right away.

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

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

在地图的情况下,每个迭代的 VAR 会给你的对象,这反过来又 getKey ()的getValue()方法。

In case of maps, every iteration the var will give you a Map.Entry object which in turn has getKey() and getValue() methods.

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

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

在特定的情况下, $ {entry.value} 实际上是一个列表,因此需要遍历它还有:

In your particular case, the ${entry.value} is actually a List, thus you need to iterate over it as well:

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

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

varStatus 是那里只是为了方便;)

The varStatus is there just for convenience ;)

要更好地理解什么是所有会在这里,这里是一个普通的Java编译:

To understand better what's all going on here, here's a plain Java translation:

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();
}

参见:



  • JSP页面

  • See also:

    • How to loop through a HashMap in JSP?
    • Show JDBC ResultSet in HTML <table> in JSP page using MVC pattern
    • How to loop over something a specified number of times in JSTL?
    • 这篇关于如何使用迭代JSTL一个HashMap里面一个ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 11:47
查看更多