简体   繁体   English

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

[英]How to iterate an ArrayList inside a HashMap using JSTL?

I have a map like this, 我有这样的地图

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

Now I have to iterate this Map and then the ArrayList inside the map. 现在,我必须迭代此Map,然后迭代该地图内的ArrayList。 How can I do this using JSTL? 如何使用JSTL做到这一点?

You can use JSTL <c:forEach> tag to iterate over arrays, collections and maps. 您可以使用JSTL <c:forEach>标记对数组,集合和映射进行迭代。

In case of arrays and collections, every iteration the var will give you just the currently iterated item right away. 如果是数组和集合,则每次迭代var都会立即为您提供当前迭代的项目。

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

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

In case of maps, every iteration the var will give you a Map.Entry object which in turn has getKey() and getValue() methods. 对于地图,每次迭代时var都会为您提供一个Map.Entry对象,该对象又具有getKey()getValue()方法。

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

In your particular case, the ${entry.value} is actually a List , thus you need to iterate over it as well: 在您的特定情况下, ${entry.value}实际上是一个List ,因此您还需要对其进行迭代:

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

The varStatus is there just for convenience ;) varStatus只是为了方便;)

To understand better what's all going on here, here's a plain Java translation: 为了更好地理解这里发生的一切,下面是一个简单的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();
}

See also: 也可以看看:

Did you try something like this? 你尝试过这样的事情吗?

<c:forEach var='item' items='${map}'>
    <c:forEach var='arrayItem' items='${item.value}' />
      ...
    </c:forEach>
</c:forEach>

you haven't closed c tag.try out this 您尚未关闭c标签。尝试一下

 <c:forEach items="${logMap}" var="entry">
        Key = ${entry.key}, values = 
        <c:forEach items="${entry.value}" var="item" varStatus="loop">
            ${item} ${!loop.last ? ', ' : ''}
        </c:forEach><br>
    </c:forEach>

You can also loop round just the map.value its self if you know the key 如果知道密钥,也可以只对map.value自身进行循环。

<c:forEach var="value" items="${myMap[myObject.someInteger]}">
    ${value}
</c:forEach>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM