Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jstl foreach directly over the values of a map?

Tags:

jsp

jstl

I tried the following which surprisingly does not work, looks like .values does not work at all in jstl:

<c:forEach var="r" items="${applicationScope['theMap'].values}">

The map is defined like this (and later saved to the ServletContext):

Map<Integer, CustomObject> theMap = new LinkedHashMap<Integer, CustomObject>();

How to get this working? I actually really would like to avoid modifying what's inside of the foreach-loop.

like image 615
Yves Avatar asked May 28 '11 21:05

Yves


People also ask

How do I iterate over a map in JSTL?

You can use the same technique to loop over a HashMap in JSP which we have used earlier to loop over a list in JSP. The JSTL foreach tag has special support for looping over Map, it provides you both key and value by using var attribute. In the case of HashMap, object exported using var contains Map. Entry object.

How to iterate list of HashMap in JSP using JSTL?

You can use JSTL <c:forEach> tag to iterate over arrays, collections and maps. In case of arrays and collections, every iteration the var will give you just the currently iterated item right away. In case of maps, every iteration the var will give you a Map.

What is varStatus in ForEach of JSTL?

The varStatus variables give the user the means to refer to: the first row/node returned by a ForEach Tag; the last row/node returned by a ForEach Tag; the count of the current row/node returned by a ForEach Tag; and the index of the current row/node returned by a ForEach Tag.

Which tag is used to iterate over a list of items in JSP?

JSTL foreach tag allows you to iterate or loop Array List, HashSet or any other collection without using Java code. After the introduction of JSTL and expression language(EL) it is possible to write dynamic JSP code without using scriptlet which clutters jsp pages.


1 Answers

So you want to iterate over map values? Map doesn't have a getValues() method, so your attempt doesn't work. The <c:forEach> gives a Map.Entry back on every iteration which in turn has getKey() and getValue() methods. So the following should do:

<c:forEach var="entry" items="${theMap}">
    Map value: ${entry.value}<br/>
</c:forEach>

Since EL 2.2, with the new support for invoking non-getter methods, you could just invoke Map#values() directly:

<c:forEach var="value" items="${theMap.values()}">
    Map value: ${value}<br/>
</c:forEach>

See also:

  • How to loop over a Map using <c:forEach>?
like image 122
BalusC Avatar answered Sep 20 '22 01:09

BalusC