Thursday, March 25, 2010

Preserving structure sort order in ColdFusion

ColdFusion doesn't preserve the order in which elements were assigned to the structure. If you want to quickly and consistently loop through the items in a structure in the order in which they were assigned, the answer is simply to not use a ColdFusion structure. It's easier (and less stupid) than it sounds.

Instead of this:
<cfset mystruct = StructNew() />

Do this:

<cfset mystruct = createObject("java", "java.util.LinkedHashMap").init() />

A java LinkedHashMap object can be treated exactly the same as a structure created by StructNew(). You can assign values the same way, and you can even loop over it the same way using <cfloop collection="...">. Need to do a StructSort? You can do that, too. The only difference is that cfloop will loop over it in the order in which the elements were assigned.