如何使用JSTL在HashMap中迭代ArrayList? [英] How to iterate an ArrayList inside a HashMap using JSTL?

查看:162
本文介绍了如何使用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?

推荐答案

您可以使用 JSTL < c:forEach> 标签遍历数组,集合和地图。

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} 实际上是一个列表,因此您还需要遍历它:

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



另请参见:



查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆