Sorting an array of String with custom ordering
final String ORDER= "FCBWHJLOAQUXMPVINTKGZERDYS";
Arrays.sort(str, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return ORDER.indexOf(o1) - ORDER.indexOf(o2) ;
}
});
You can also add:
o1.toUpperCase()
If your array is case in-sensitive.
Apparently the OP wants to compare not only letters but strings of letters, so it's a bit more complicated:
public int compare(String o1, String o2) {
int pos1 = 0;
int pos2 = 0;
for (int i = 0; i < Math.min(o1.length(), o2.length()) && pos1 == pos2; i++) {
pos1 = ORDER.indexOf(o1.charAt(i));
pos2 = ORDER.indexOf(o2.charAt(i));
}
if (pos1 == pos2 && o1.length() != o2.length()) {
return o1.length() - o2.length();
}
return pos1 - pos2 ;
}
I would do something like this:
Put the letters in a HashTable (let's call it orderMap). Key is the letter, value is the index in ORDER.
And then:
Arrays.sort(str, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
int length = o1.length > o2.length ? o1.length: o2.length
for(int i = 0; i < length; ++i) {
int firstLetterIndex = orderMap.get(o1.charAt(i));
int secondLetterIndex = orderMap.get(o2.charAt(i));
if(firstLetterIndex == secondLetterIndex) continue;
// First string has lower index letter (for example F) and the second has higher index letter (for example B) - that means that the first string comes before
if(firstLetterIndex < secondLetterIndex) return 1;
else return -1;
}
return 0;
}
});
For making it case-insensitive just do toUpperCase() to both strings at the beginning.