You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@velocity.apache.org by Mark Becker <mb...@webelite.com> on 2003/03/20 16:22:32 UTC

foreach in reverse?

Hi,

I need some help with a Velocity foreach problem.  Or it might be a Java Hashtable/Set problem, I'm not sure...

My app includes a form that has a few SELECT fields that are built from lookup tables in the database.

I have a method in the controller "getCategoryList()" that does the lookup, and returns a Hashtable that maps the names of each category to its Primary Key ID in the database.  (ID is key of Hashtable, names are Values.)  Then, to build the SELECT field, I'm doing this:

<TD><SELECT NAME="category_id">
    #set ( $categoryList = $controller.getCategoryList() )
    #foreach ( $categoryId in $categoryList.keySet() )
        <OPTION VALUE="$!categoryId">$!categoryList.get($categoryId)</OPTION>
    #end
    </SELECT>
</TD>

This is working, but for some reason, it's printing the list out in reverse order!  (I.E. from highest $categoryId to lowest.)

Is there any way for me to turn this around?  I've already tried using ORDER BY statements in the SQL, and that doesn't seem to make a difference...

MEB


---------------------------------------------------------------------
To unsubscribe, e-mail: velocity-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: velocity-user-help@jakarta.apache.org


Re: foreach in reverse?

Posted by Claude Brisson <cl...@savoirweb.com>.
This issue has already been discussed not a long time ago in the list...

> It you want to retain ordering you should use a List collection or
> something similar, if you're dead-set on using a key->value you could
> use a TreeMap which guarantees ascending key order.

Or if you're using the JDK1.4, your controller can return a LinkedHashMap instead of a HashMap.

CloD




---------------------------------------------------------------------
To unsubscribe, e-mail: velocity-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: velocity-user-help@jakarta.apache.org


Re: foreach in reverse?

Posted by Dave Newton <da...@solaraccess.com>.
On Thu, 2003-03-20 at 10:22, Mark Becker wrote:
> I need some help with a Velocity foreach problem.  Or it might be 
> a Java Hashtable/Set problem

It's not a problem, it's just that hashing doesn't preserve order. In
fact in some of the java hash classes the order doesn't even have to
remain constant.

It you want to retain ordering you should use a List collection or
something similar, if you're dead-set on using a key->value you could
use a TreeMap which guarantees ascending key order.

Dave



---------------------------------------------------------------------
To unsubscribe, e-mail: velocity-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: velocity-user-help@jakarta.apache.org