我有一个String
数组:
String[] str = {"ab" , "fog", "dog", "car", "bed"};
Arrays.sort(str);
System.out.println(Arrays.toString(str));
Run Code Online (Sandbox Code Playgroud)
如果我使用Arrays.sort
,输出是:
[ab, bed, car, dog, fog]
Run Code Online (Sandbox Code Playgroud)
但我需要实现以下排序:
FCBWHJLOAQUXMPVINTKGZERDYS
我想我需要实现Comparator
和覆盖compare
方法:
Arrays.sort(str, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
// TODO Auto-generated method stub
return 0;
}
});
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?
Maj*_*ssi 32
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) ;
}
});
Run Code Online (Sandbox Code Playgroud)
您还可以添加:
o1.toUpperCase()
Run Code Online (Sandbox Code Playgroud)
如果你的阵列是敏感的.
显然,OP不仅要比较字母而且要比较字母串,所以它有点复杂:
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 ;
}
Run Code Online (Sandbox Code Playgroud)
我会做这样的事情:
将字母放入哈希表(我们称之为 orderMap)。键是字母,值是 ORDER 中的索引。
进而:
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;
}
});
Run Code Online (Sandbox Code Playgroud)
为了使其不区分大小写,只需在开头对两个字符串执行 toUpperCase() 即可。