125

I'm looking to have JSTL loop through a Map<String, String> and output the value of the key and it's value.

For example I have a Map<String, String> which can have any number of entries, i'd like to loop through this map using JSTL and output both the key and it's value.

I know how to access the value using the key, ${myMap['keystring']}, but how do I access the key?

blackpanther
  • 10,998
  • 11
  • 48
  • 78
Dean
  • 1,261
  • 2
  • 8
  • 4
  • Related: http://stackoverflow.com/questions/2117557/how-to-iterate-an-arraylist-inside-a-hashmap-using-jstl – BalusC May 19 '10 at 14:29

2 Answers2

284

Like this:

<c:forEach var="entry" items="${myMap}">
  Key: <c:out value="${entry.key}"/>
  Value: <c:out value="${entry.value}"/>
</c:forEach>
cletus
  • 616,129
  • 168
  • 910
  • 942
6

You can loop through a hash map like this

<%
ArrayList list = new ArrayList();
TreeMap itemList=new TreeMap();
itemList.put("test", "test");
list.add(itemList);
pageContext.setAttribute("itemList", list);                            
%>

  <c:forEach items="${itemList}" var="itemrow">
   <input  type="text"  value="<c:out value='${itemrow.test}'/>"/>
  </c:forEach>               

For more JSTL functionality look here

Dexygen
  • 12,287
  • 13
  • 80
  • 147
sayan
  • 242
  • 2
  • 2
  • 35
    Don't use scriplets. They are bad. – tad Aug 03 '12 at 21:11
  • @tad I've also heard that. But why? – TJ- Oct 16 '12 at 06:47
  • 7
    @TJ- As a general rule, there are few good reasons to put powerful logic in your templates; they are hard to debug, they mix paradigms, and they can produce unexpected results. Besides, the JSTL aready provides a facility to cleanly iterate over maps: the forEach tag. – tad Oct 16 '12 at 17:55
  • 14
    @tad he's obviously using scriplets to set up his test data. This was a perfectly good answer – jk. Jul 11 '14 at 18:54
  • 7
    @jk: I agree. The downvotes here are pretty ridic. Also, the idea that scriptlets can produce unexpected results makes no sense to me. They're not pretty, but 1+1 always equals 2, unless there are some specific scenarios I'm not aware of. – IcedDante Oct 16 '14 at 19:05
  • @jk. - while the use of a scriptlet to show the setup for the example is reasonable, expecting your data to be provided as a list of maps with constant keys rather than a map between the actual items you care about is a particularly poor solution to the problem, and I imagine that a lot of people are therefore assuming that the scriptlet is intended to show how to *transform* an existing map into a list, rather than as a way of showing example data. – Jules Feb 20 '18 at 20:38