Re: sorting strings with embedder digits
On Thu, 26 Nov 2009, Donkey Hottie wrote:
On 26.11.2009 18:25, tony wrote:
Currently I need to sort a list of filenames such as 'track 11.mp3',
'track 4.mp3'. My problem is that a simple sort will put track 11
first because it's alphabetical. My approach seems tortuous - split
around any digits, then from there build an array holding each part in
turn. Once that is done, you can compare the array entries and where
digits are involved, compare them numerically.
Does anyone know of a neater way to do this?
Sure. A custom Comparator. Should be quite straightforward.
It'll have to do the same work under the hood, though, so i don't see why
it would be any more straightforward than what Tony is currently doing.
Still, it's a way of packaging the logic, and it might be neater than
however he currently has it packaged.
I'd suggest implementing a Collator rather than a Comparator, so you can
make CollationKeys, and so avoid having to repeat the analysis of the
strings for each comparison. Having written your FilenameCollator, you can
do:
public void sortUsingCollator(List<String> strings, Collator collator) {
CollationKey[] keys = new CollationKey[strings.size()];
for (int i = 0; i < keys.length; ++i) {
keys[i] = collator.getCollationKey(string);
}
Arrays.sort(keys);
for (int i = 0; i < keys.length; ++i) {
strings.set(i, keys[i].getSourceString());
}
}
It's a shame there isn't a method to do this in the standard library (is
there?), since it's absolutely generic.
tom
--
IME the only lousy shags are when she says no! -- John Rowland