如何使用 JSTL 在 HashMap 中迭代 ArrayList?
我有一张这样的地图,
Map<Integer,ArrayList<Object>> myMap = new LinkedHashMap<Integer,ArrayList<Object>>();
现在我必须迭代这个 Map,然后迭代 Map 中的 ArrayList.如何使用 JSTL 执行此操作?
Now I have to iterate this Map and then the ArrayList inside the map. How can I do this using JSTL?
您可以使用 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
都会给你一个 Map.Entry
对象,该对象依次具有 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}
实际上是一个 List
,因此您也需要对其进行迭代:
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
只是为了方便;)
为了更好地理解这里发生的一切,这里是一个简单的 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();
}