Sorting with Collators
January 8, 2012 Leave a Comment
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.

