I'm trying to create a very simple IRC client in java for fun and have just started dealing with channel specific user lists. I'm using the following code to sort the user list, but it doesn't sort it exactly as it should. IRC hierarchy goes like this: ~ & @ % + (qaohv), and if someone doesn't have one of those prefixes they should be at the bottom of the user list. Does anybody know what I could do to retain the alphabetical order and rank order of a list with one comparator?
Comparator code:
public class StringComparator implements Comparator<String> {
@Override
public int compare(String a, String b) {
return a.compareToIgnoreCase(b);
}
}
Example output of above comparator:
%Brennan
&Adam
&Sheldon
+Mike
+Yoda
@Phil
@Unleashed
Jean
Damien
~Tim
You need to handle the cases of the prefixes before doing the alphabetic comparison:
public class StringComparator implements Comparator<String> {
@Override
public int compare(String a, String b) {
int pfx = betterPrefix(a[0],b[0]);
if (pfx != 0)
return pfx;
return a.compareToIgnoreCase(b);
}
private int betterPrefix(char a, char b) {
String prefixOrder = "@%&+"
int idxa = prefixOrder.indexOf(a);
if (idxa < 0) idxa = prefixOrder.length();
int idxb = prefixOrder.indexOf(b);
if (idxb < 0) idxb = prefixOrder.length();
return idxa - idxb;
}
}
Here I suppose that the two string are not empty, but you should test for it.