更新时间:2022-12-10 08:40:30
您可以建立自己的比较器:
You can build your own Comparator:
import java.util.Comparator;
public class MyComparator implements Comparator<String> {
private int[] charRank;
public MyComparator() {
char[] charOrder = {'Q','W','E','R','T','Y','U','I','O','P','L','K','J','H','G','F','D','S','A','Z','X','C','V','B','N','M'};
this.charRank = new int[26];
for(int i=0; i<25; i++) {
this.charRank[charToInt(charOrder[i])] = i;
}
}
public int compare(String s1, String s2) {
// returns
// Positive integer if s1 greater than s2
// 0 if s1 = s2
// Negative integer if s1 smaller than s2
s1 = s1.toUpperCase();
s2 = s2.toUpperCase();
int l = Math.min(s1.length(), s2.length());
int charComp;
for(int i=0; i<l; i++) {
charComp = this.charRank[charToInt(s1.charAt(i))] - charRank[charToInt(s2.charAt(i))];
if(charComp != 0)
return charComp;
}
return s1.length() - s2.length();
}
//works for c between 'A' and 'Z' - upper case letters
private static int charToInt(char c) {
return c - 65;
}
//works for 0<=i<=25
private static char intToChar(int i) {
return (char) (i + 65);
}
}
然后,你只需要运行:
Arrays.sort(entryArray, new MyComparator());
现在有一些解释。
构造函数MyComparator为每个字母构建一系列排名。在实践中,它将以 {18,23,21,...}
开头,因为'A'位于第18位,'B'位于第23位...
The constructor of MyComparator builds an array of ranks for each of your letter. In practice it will begin with {18, 23, 21, ... }
because 'A' is in the 18th place, 'B' in the 23rd...
然后,比较两个字符串 s1
和 s2
,字符在字典顺序中逐一进行比较。
Then, when you compare two strings s1
and s2
, characters are compared in the lexicographic order one by one.
n
字符相同,现在,您比较 c1
和 c2
。如果 c1
的排名低于 c2
的排名,则必须返回一个负整数,因为 s1
在字典顺序中 s2
之前( s1
小于 S2
)。如果 c1
的排名大于 c2
的排名,则相反。如果两个等级都等于 c1
并且 c2
等于,则必须查看下一个字符。 s1
更短,它在字典顺序中排在第一位,它更小,你必须返回一个负整数。n
characters are identical, and now, you compare c1
and c2
. If the rank of c1
is lower than then rank of c2
, then you have to return a negative integer since s1
comes before s2
in the lexicographic order (s1
is smaller than s2
). If the rank of c1
is greater than the rank of c2
, it is the contrary. If both ranks are equals c1
and c2
are equals and you have to look at the next character.s1
is shorter, it comes first in the lexicographic order, it is smaller, you have to return a negative integer.在这里你走了。我希望这是你在等待的。
And here you go. I hope it was what you were waiting for.
@Edit: s1 = s1.toUpperCase()
是只是为了避免区分大小写字母的痛苦。如果您更喜欢使用小写字母,只需将其更改为 s1 = s1.toLowerCase()
,更改方法 intToChar
到返回c-97
(小写'a'的ascii代码)自然地,指定 charOrder
构造函数中的数组使用小写字母。
@ the s1 = s1.toUpperCase()
is just to avoid the pain to distinguish upper and lower case letters. If you prefer to work with lower case letters, just change it to s1 = s1.toLowerCase()
, change the method intToChar
to return c-97
(ascii code for a lower case 'a') and naturally, specify the charOrder
array in the constructor using lower case letters.