我有一个String
数组:
String[] str = {"ab" , "fog", "dog", "car", "bed"};
Arrays.sort(str);
System.out.println(Arrays.toString(str));
如果我使用Arrays.sort
,则输出为:
[ab, bed, car, dog, fog]
但我需要实现以下排序:
FCBWHJLOAQUXMPVINTKGZERDYS
我认为我需要实施Comparator
并覆盖compare
方法:
Arrays.sort(str, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
// TODO Auto-generated method stub
return 0;
}
});
我该如何解决这个问题?
答案 0 :(得分: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) ;
}
});
您还可以添加:
o1.toUpperCase()
如果您的阵列是区分大小写的。
显然,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 ;
}
答案 1 :(得分:4)
我会做这样的事情:
将字母放在HashTable中(让我们称之为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;
}
});
为了使它不区分大小写,只需在开头为两个字符串添加toUpperCase()。
答案 2 :(得分:0)
在这里你可以找到有用的链接:
Using comparator to make custom sort
在你的例子中,比较你需要的类的特定属性,以检查基准字符串中的char的可能性,并基于此检查它是否更好/相等/更小。
答案 3 :(得分:0)
花时间改进所选答案。这更有效率
public static void customSort(final String order,String[] array){
String[] alphabets={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","0","1","2","3","4","5","6","7","8","9"};
String keyword=order;
for(int g=0; g<alphabets.length; g++){
String one=alphabets[g];
if(!keyword.toUpperCase().contains(one)){keyword=keyword+one;}
}
final String finalKeyword=keyword;
Arrays.sort(array, new Comparator<String>() {
@Override
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 = finalKeyword.toUpperCase().indexOf(o1.toUpperCase().charAt(i));
pos2 = finalKeyword.toUpperCase().indexOf(o2.toUpperCase().charAt(i));
}
if (pos1 == pos2 && o1.length() != o2.length()) {
return o1.length() - o2.length();
}
return pos1 - pos2 ;
}
});
//Arrays.sort(array, Collections.reverseOrder());
}