tags:

views:

3563

answers:

3

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

+2  A: 

When you are using forEach to create an integer loop, you can go forward or backward:

<c:forEach var="i" begin="10" end="0" step="-1">
    ....
</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.

Eddie
In my case it's a Collection
Steve Kuo
I updated my answer to add a code sample for how I've iterated over a Collection in a desired order.
Eddie
or better yet, create the collection in the order it will be used in. jsps are not good places for data massaging.
Chii
Yow, -1 for showing someone how to do something? We're only allowed to show the ideal way? Geez.
Eddie
+2  A: 

I would like to add a bit to Eddie's answer. Order reverse/forward doesn't make sense for few collections, as they don't maintain or guarantee any ordering. Your best bet is to sort it in your POJO and then get it in your JSP. Using Scriptlets is a bad idea.

Adeel Ansari
+1  A: 

You could also consider rolling a custom JSTL function that returned a reversed copy of your list, backed by something like this:

public static <T extends Object> List<T> reverse(List<T> list) {
    List<T> copy = Collections.emptyList();
    Collections.copy(copy, list);
    Collections.reverse(copy);
    return copy;
}

Doesn't work for Collections, but as mentioned in another answer, the concept of ordering is a bit vague for some collections.

harto