Sorting with Collators

I learned an interesting thing this week.  I had to sort a set of query results according to these rules:  object names starting with lowercase letters should precede object names starting with uppercase letters, and object names starting with numbers should follow those staring with uppercase letters.  In pseudo-code, the rule looks like this:  [a-z] < [A-Z] < [0-9].  As you might have noticed, this is exactly the reverse of how strings are naturally sorted (i.e., according to the ASCII table).  So, what I learned is that it is very simple to create a rule-based collator object that defines sort orders and use it to enable this sort.

The code looks like this:

RuleBasedCollator coll = new RuleBasedCollator(
“< a,A < b,B < c,C < d,D < e,E < f,F < g,G < h,H <i,I ” +
“< j,J < k,K < l,L < m,M < n,N < o,O < p,P < q,Q < r,R ” +
“< s,S < t,T < y,U < v,V < w,W < x,X < y,Y < z,Z ” +
“< 0 < 1 < 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9”);
Collections.sort(list_of_objects, coll);

where list_of_objects is a ListArray of object names.

Simple, clean and uses built-in Java sorting logic.  The nice thing about collators, is you can create any sorting precedent you want.  For example, if you wanted to swap the precedence of S and T in the collation above, simple change the order in the definition of the collator and Voila!, your strings will now sort such that T precedes S.

If you want more on collators, check here.


About Scott
I have been implementing Documentum solutions since 1997. In 2005, I published a book about developing Documentum solutions for the Documentum Desktop Client (ISBN 0595339689). In 2010, I began this blog as a record of interesting and (hopefully) helpful bits of information related to Documentum, and as a creative outlet.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: