I have array of strings: 15MB,12MB, 1TB,1GB. I want to compare them lexicographically by just following the rule that MB are smaller than GB and TB. So at the end I want to get: 12MB,15MB,1GB,1TB. I found a way to compare the letters:
final static String ORDER="MGT";
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'm thinking of splitting the string by numbers and letter but then how can I sort them by their letters "MB.." and then by their numbers. Do I use two comparators or something else?