11

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.

Yves
  • 171
  • 1
  • 1
  • 5
  • possible duplicate of [JSTL access a map value by key](http://stackoverflow.com/questions/924451/jstl-access-a-map-value-by-key) – duffymo May 28 '11 at 21:54
  • @duffy: I understand that the OP wants to iterate over all values without knowing the keys. – BalusC May 28 '11 at 22:18
  • 1
    @BalusC: Yes I do :-) But anyway I get the keys. It might sound strange, but in this case, the key is also included in the value. The key as in is the primary key of the value object. – Yves May 29 '11 at 19:22
  • I am totally lost now. So my answer didn't help you? What's the functional requirement then? – BalusC May 29 '11 at 19:24
  • The answer was absolutely ok. There is no getValues(), and this is the issue I have. Will have to work around it :) – Yves May 29 '11 at 19:28

3 Answers3

37

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:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
9

you can iterate a map in jstl like following

<c:forEach items="${numMap}" var="entry">
  ${entry.key},${entry.value}<br/>
</c:forEach>
Brad Larson
  • 170,088
  • 45
  • 397
  • 571
2

Also you can use this type if necessary

<c:forEach var="key" items="${theMap.keySet()}" varStatus="keyStatus">
    <c:set var="value" value="${theMap[key]}" />
</c:forEach>
mehmet cinar
  • 160
  • 1
  • 7