Is it possible to create exception rule in Comparator sort order?
I have been working on trying to learn how to use Comparators to sort Collections... In one of my recent experiments, I tried to order a PriorityQueue of String elements alphabetically, in ascending order, with one exception: any word beginning with the letter "z" should be given a higher priority than any other word. I haven't been able to find a way to do this, nor to discern whether or not it's possible.
Any help is appreciated.
# 1
Try something like this:public class MyComparator implements Comparator<String> {
@Override
public int compare(String s1, String s2) {
boolean s1StartsWithZ = s1.startsWith("z");
boolean s2StartsWithZ = s2.startsWith("z");
if (s1StartsWithZ && !s2StartsWithZ) return 1;
if (s2StartsWithZ && !s1StartsWithZ) return -1;
return s1.compareTo(s2);
}
}
dwga at 2007-7-12 18:27:33 >

# 2
Please note that for "alphabetical" sorting to take place, you should really use a Collator, not Comparator<String> (it will compare unicodes, so A-Z comes before a-z, for example).