Using JSTL's forEach
tag, is it possible to iterate in reverse order?
views:
3563answers:
3When 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.
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.
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.