You are viewing a plain text version of this content. The canonical link for it is here.
Posted to taglibs-user@tomcat.apache.org by Hao Ding <hd...@it.canterbury.ac.nz> on 2002/10/18 05:15:16 UTC

print out the items of a collection in reverse order

Hi all,

Is there a way to print out the items of a collection (e.x an array) in 
reverse order using <c:forEach> or some other JSTL core tags?

Thanks
Hao


--
To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>


Re: print out the items of a collection in reverse order

Posted by Shawn Bayern <ba...@essentially.net>.
On Fri, 18 Oct 2002, Hao Ding wrote:

> Is there a way to print out the items of a collection (e.x an array)
> in reverse order using <c:forEach> or some other JSTL core tags?

Not as such.  But since you ask, one solution does occur to me:

You can loop through the collection with <c:forEach> the first time and
add elements to a SortedMap with a key derived from the negation of the
current 'count', then loop through this new SortedMap.  (To do this
properly, you'd need first to determine the collection's size.  Then,
you'd need to produce each new key with <fmt:formatNumber> based in part
on this size, for keys set by <c:set target="..." property="..."> are
always textual, and numerical keys won't, by default, sort lexically the
way you want them to.  To put it another way, you need to pad the numbers
with zeroes by using 'minIntegerDigits'.)

Thus, one solution that prints out the elements of an array or List named
'original' in reverse order could look like this:

 <jsp:useBean id="reversed" class="java.util.TreeMap" />
 <c:forEach items="${original}" var="item" varStatus="s">
  <c:set var="size" value="${s.count}" />
 </c:forEach>
 <c:forEach items="${foo}" var="item" varStatus="s">
  <fmt:formatNumber value="${size-s.count}"
    minIntegerDigits="${size/10 + 1}" var="n" />
  <c:set target="${reversed}" property="${n}" value="${item}" />
 </c:forEach>
 <c:forEach items="${reversed}" var="item">
  <c:out value="${item.value}" />
 </c:forEach>

However, I think we're long past the point where it's easier to do this in
a servlet or some other backing Java code.  :-)

-- 
Shawn Bayern
"JSTL in Action"   http://www.jstlbook.com


--
To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>