Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSTL forEach reverse order

Tags:

java

jsp

jstl

Using JSTL's forEach tag, is it possible to iterate in reverse order?

like image 221
Steve Kuo Avatar asked Apr 02 '09 23:04

Steve Kuo


Video Answer


1 Answers

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.

like image 175
Eddie Avatar answered Sep 25 '22 15:09

Eddie