Using JSTL's forEach
tag, is it possible to iterate in reverse order?
When you are using forEach
to create an integer loop, you can go forward or backward, but it requires some work. It turns out you cannot do this, for example:
<c:forEach var="i" begin="10" end="0" step="-1"> .... </c:forEach>
because the spec requires the step is positive. But you can always loop in forward order and then use <c:var
to convert the incrementing number into a decrementing number:
<c:forEach var="i" begin="0" end="10" step="1"> <c:var var="decr" value="${10-i}"/> .... </c:forEach>
However, when you are doing a forEach
over a Collection of any sort, I am not aware of any way to have the objects in reverse order. At least, not without first sorting the elements into reverse order and then using forEach
.
I have successfully navigated a forEach
loop in a desired order by doing something like the following in a JSP:
<% List list = (List)session.getAttribute("list"); Comparator comp = .... Collections.sort(list, comp); %> <c:forEach var="bean" items="<%=list%>"> ... </c:forEach>
With a suitable Comparator, you can loop over the items in any desired order. This works. But I am not aware of a way to say, very simply, iterate in reverse order the collection provided.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With